Query for values (not objects) in list with MongoDB

To query for values in list, use the positional operator ($) in MongoDB. The $ operator projects only the first matching array element that satisfies the query condition.

Syntax

db.collection.find(
    { "arrayField": "value" },
    { "arrayField.$": 1 }
);

Sample Data

Let us create a collection with documents ?

db.demo628.insertMany([
    { id: 1, Name: ["Chris", "David", "John"] },
    { id: 1, Name: ["Carol", "Sam"] },
    { id: 2, Name: ["Mike", "Sam", "John"] }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e9ae7ea6c954c74be91e6b6"),
        ObjectId("5e9ae7f26c954c74be91e6b7"),
        ObjectId("5e9ae8056c954c74be91e6b8")
    ]
}

Display all documents from a collection with the help of find() method ?

db.demo628.find();
{ "_id": ObjectId("5e9ae7ea6c954c74be91e6b6"), "id": 1, "Name": ["Chris", "David", "John"] }
{ "_id": ObjectId("5e9ae7f26c954c74be91e6b7"), "id": 1, "Name": ["Carol", "Sam"] }
{ "_id": ObjectId("5e9ae8056c954c74be91e6b8"), "id": 2, "Name": ["Mike", "Sam", "John"] }

Example: Query for Values in List

Query for values (not objects) in list ?

db.demo628.find(
    { "Name": "John" },
    { "id": 1, "Name.$": 1 }
);
{ "_id": ObjectId("5e9ae7ea6c954c74be91e6b6"), "id": 1, "Name": ["John"] }
{ "_id": ObjectId("5e9ae8056c954c74be91e6b8"), "id": 2, "Name": ["John"] }

Key Points

  • The $ operator returns only the first matching element from the array
  • Use "arrayField.$": 1 in the projection to get the matched value
  • The query condition must match at least one array element for the document to be returned

Conclusion

The positional operator $ allows you to project specific array values that match your query condition. This is useful when you need to retrieve only the matching array elements instead of the entire array.

Updated on: 2026-03-15T03:12:37+05:30

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements