How can I use $elemMatch on first level array in MongoDB?

You can use $in operator instead of $elemMatch on first level array. For simple value matching in arrays, $in provides better performance and cleaner syntax.

Syntax

db.collection.find({
    "arrayField": { $in: ["value1", "value2"] }
});

Sample Data

Let us create a collection with documents containing first−level arrays ?

db.firstLevelArrayDemo.insertMany([
    {
        "StudentName": "Chris",
        "StudentTechnicalSkills": ["MongoDB", "MySQL", "SQL Server"]
    },
    {
        "StudentName": "Robert", 
        "StudentTechnicalSkills": ["C", "Java", "C++"]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5ca2360f66324ffac2a7dc71"),
        ObjectId("5ca2362766324ffac2a7dc72")
    ]
}

Example: Query First Level Array

Find students who have "MongoDB" as a technical skill ?

db.firstLevelArrayDemo.find({
    "StudentTechnicalSkills": { $in: ["MongoDB"] }
});
{
    "_id": ObjectId("5ca2360f66324ffac2a7dc71"),
    "StudentName": "Chris",
    "StudentTechnicalSkills": [
        "MongoDB",
        "MySQL", 
        "SQL Server"
    ]
}

Key Points

  • $in matches documents where the array field contains any of the specified values.
  • For first−level arrays with simple values, $in is more efficient than $elemMatch.
  • $elemMatch is typically used for arrays containing objects or complex matching conditions.

Conclusion

Use $in operator for matching values in first−level arrays. It provides simpler syntax and better performance compared to $elemMatch for basic value matching scenarios.

Updated on: 2026-03-15T00:42:56+05:30

312 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements