Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.$": 1in 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.
Advertisements
