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
Search array of objects in a MongoDB collection?
To search array of objects in MongoDB, use the find() method with dot notation to target specific fields within array elements. The find() method selects documents in a collection and returns a cursor to the matched documents.
Syntax
db.collection.find({
"arrayField.objectProperty": "value"
});
// Multiple conditions with $or
db.collection.find({
$or: [
{"arrayField.property1": "value1", "arrayField.property2": "value2"},
{"arrayField.property1": "value3", "arrayField.property2": "value4"}
]
});
Sample Data
Let us create a collection with documents containing arrays of objects ?
db.demo484.insertMany([
{
"id": 1,
"details": [
{ "Name1": "Chris" },
{ "Name2": "David" },
{ "Name3": "Bob" }
]
},
{
"id": 2,
"details": [
{ "Name1": "Chris" },
{ "Name2": "Carol" },
{ "Name3": "Bob" }
]
},
{
"id": 3,
"details": [
{ "Name1": "Chris" },
{ "Name2": "Carol" },
{ "Name3": "Mike" }
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e82e3a4b0f3fa88e22790a1"),
ObjectId("5e82e3a4b0f3fa88e22790a2"),
ObjectId("5e82e3a4b0f3fa88e22790a3")
]
}
Display all documents from the collection ?
db.demo484.find();
{ "_id": ObjectId("5e82e3a4b0f3fa88e22790a1"), "id": 1, "details": [ { "Name1": "Chris" }, { "Name2": "David" }, { "Name3": "Bob" } ] }
{ "_id": ObjectId("5e82e3a4b0f3fa88e22790a2"), "id": 2, "details": [ { "Name1": "Chris" }, { "Name2": "Carol" }, { "Name3": "Bob" } ] }
{ "_id": ObjectId("5e82e3a4b0f3fa88e22790a3"), "id": 3, "details": [ { "Name1": "Chris" }, { "Name2": "Carol" }, { "Name3": "Mike" } ] }
Example: Search Array Objects with Multiple Conditions
Find documents where Name2 is "Carol" and Name3 is either "Mike" or "Bob" ?
db.demo484.find({
$or: [
{"details.Name2": "Carol", "details.Name3": "Mike"},
{"details.Name2": "Carol", "details.Name3": "Bob"}
]
});
{ "_id": ObjectId("5e82e3a4b0f3fa88e22790a2"), "id": 2, "details": [ { "Name1": "Chris" }, { "Name2": "Carol" }, { "Name3": "Bob" } ] }
{ "_id": ObjectId("5e82e3a4b0f3fa88e22790a3"), "id": 3, "details": [ { "Name1": "Chris" }, { "Name2": "Carol" }, { "Name3": "Mike" } ] }
Key Points
- Use dot notation (
arrayField.objectProperty) to search within array objects. - MongoDB searches across all array elements automatically.
- Use
$orfor multiple condition combinations.
Conclusion
Search arrays of objects using dot notation to target specific properties within array elements. Combine multiple conditions with $or operator for flexible queries across array object fields.
Advertisements
