MongoDB Query to Find Documents Where Array Contains Value
{ arrayField: value } in MongoDB to find documents where the array arrayField contains the specified value.Examples
How to Think About It
{ arrayField: value }.Algorithm
Code
db.products.insertMany([
{ _id: 1, tags: ["mongodb", "database"] },
{ _id: 2, tags: ["nosql", "database"] },
{ _id: 3, tags: ["mongodb"] }
]);
const query = { tags: "mongodb" };
const result = db.products.find(query).toArray();
printjson(result);Dry Run
Let's trace the query { tags: "mongodb" } through the code
Insert documents
Documents inserted with tags arrays: ["mongodb", "database"], ["nosql", "database"], ["mongodb"]
Run query
Find documents where tags array contains "mongodb"
Return results
Documents with _id 1 and 3 match and are returned
| _id | tags | Contains 'mongodb'? |
|---|---|---|
| 1 | ["mongodb", "database"] | Yes |
| 2 | ["nosql", "database"] | No |
| 3 | ["mongodb"] | Yes |
Why This Works
Step 1: Simple matching
MongoDB matches array fields by checking if the array contains the value directly using { arrayField: value }.
Step 2: No special operator needed
You do not need to use special operators like $elemMatch for simple value containment.
Step 3: Efficient query
This query is efficient because MongoDB can use indexes on array fields to speed up the search.
Alternative Approaches
db.products.find({ tags: { $elemMatch: { $eq: "mongodb" } } })db.products.find({ tags: { $in: ["mongodb"] } })Complexity: O(n) time, O(k) space
Time Complexity
The query scans documents and checks array fields, which is O(n) where n is number of documents. Indexes on array fields can improve this.
Space Complexity
The query uses O(k) space where k is number of matching documents returned.
Which Approach is Fastest?
Direct matching { arrayField: value } is fastest for simple containment. Alternatives add overhead for complex conditions.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct match { arrayField: value } | O(n) | O(k) | Simple value containment |
| $elemMatch operator | O(n) | O(k) | Multiple conditions inside array elements |
| $in operator | O(n) | O(k) | Matching any value from a list |
{ arrayField: value } without extra operators.$elemMatch unnecessarily for simple value checks inside arrays.