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
Can we search an array of objects in MongoDB?
Yes, you can search an array of objects in MongoDB using multiple approaches. The most common methods are direct field matching and the aggregation pipeline with $unwind.
Syntax
// Direct field matching
db.collection.find({"arrayField.fieldName": "value"})
// Using aggregation with $unwind
db.collection.aggregate([
{$unwind: "$arrayField"},
{$match: {"arrayField.fieldName": "value"}}
])
Sample Data
db.demo623.insertOne({
_id: 1,
details: [
{
Name: "Chris"
},
{
DueDate: new ISODate("2020-01-10")
},
{
CountryName: "US"
}
]
});
{ "acknowledged" : true, "insertedId" : 1 }
Method 1: Using $unwind (Aggregation Pipeline)
Search for objects containing "Chris" in the Name field ?
db.demo623.aggregate([
{$unwind: "$details"},
{$match: {"details.Name": "Chris"}},
{$project: {"details.Name": 1}}
]);
{ "_id" : 1, "details" : { "Name" : "Chris" } }
Method 2: Direct Field Matching (Simpler Approach)
For most use cases, you can directly query array fields without unwinding ?
db.demo623.find({"details.Name": "Chris"});
{
"_id" : 1,
"details" : [
{ "Name" : "Chris" },
{ "DueDate" : ISODate("2020-01-10T00:00:00Z") },
{ "CountryName" : "US" }
]
}
Key Differences
- $unwind creates separate documents for each array element and allows complex filtering.
- Direct matching returns the entire document when any array element matches the condition.
Conclusion
MongoDB supports searching arrays of objects through dot notation. Use direct field matching for simple queries or the aggregation pipeline with $unwind for complex transformations and filtering.
Advertisements
