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
MongoDB "$and" operator for subcollection to fetch a document?
When working with MongoDB subcollections (arrays of documents), use $elemMatch combined with $in or $and operators to fetch documents that match specific conditions within array elements.
Syntax
// Using $in for single condition
db.collection.find({
"arrayField": {
"$elemMatch": {
"field1": "value1",
"field2": { "$in": ["value2"] }
}
}
});
// Using $and for multiple conditions
db.collection.find({
"arrayField": {
"$elemMatch": {
"$and": [
{ "field1": "value1" },
{ "field2": "value2" }
]
}
}
});
Sample Data
db.demo83.insertMany([
{
"Details": [
{
"Name": "Chris",
"Subject": ["MySQL", "MongoDB"]
},
{
"Name": "David",
"Subject": ["Java", "C"]
}
]
},
{
"Details": [
{
"Name": "Bob",
"Subject": ["C++", "Python"]
},
{
"Name": "John",
"Subject": ["Spring", "Hibernate"]
}
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e2bfd2271bf0181ecc422a3"),
ObjectId("5e2bfd4571bf0181ecc422a4")
]
}
Method 1: Using $in with $elemMatch
Find documents where a person named "Chris" studies "MongoDB" ?
db.demo83.find({
"Details": {
"$elemMatch": {
"Name": "Chris",
"Subject": { "$in": ["MongoDB"] }
}
}
});
{
"_id": ObjectId("5e2bfd2271bf0181ecc422a3"),
"Details": [
{ "Name": "Chris", "Subject": ["MySQL", "MongoDB"] },
{ "Name": "David", "Subject": ["Java", "C"] }
]
}
Method 2: Using $and with $elemMatch
Find documents using $and operator for multiple conditions ?
db.demo83.find({
"Details": {
"$elemMatch": {
"$and": [
{ "Name": "Chris" },
{ "Subject": "MongoDB" }
]
}
}
});
{
"_id": ObjectId("5e2bfd2271bf0181ecc422a3"),
"Details": [
{ "Name": "Chris", "Subject": ["MySQL", "MongoDB"] },
{ "Name": "David", "Subject": ["Java", "C"] }
]
}
Key Points
-
$elemMatchensures all conditions match within the same array element. -
$inchecks if a field value exists in a specified array of values. -
$andrequires all specified conditions to be true simultaneously.
Conclusion
Use $elemMatch with $in or $and to query subcollections effectively. $elemMatch ensures conditions match within the same array element, while $in and $and provide flexible matching criteria for complex queries.
Advertisements
