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 query to return only embedded document?
While MongoDB doesn't return only embedded documents directly, you can use projection to return specific fields and the $elemMatch operator to filter array elements that match certain conditions.
Syntax
db.collection.find(
{ "arrayField.nestedField": { $gte: value } },
{ "arrayField": { $elemMatch: { "nestedField": { $gte: value } } } }
);
Sample Data
db.queryToEmbeddedDocument.insertOne({
"UserName": "Larry",
"PostDetails": [
{ "UserMessage": "Hello", "UserLikes": 8 },
{ "UserMessage": "Hi", "UserLikes": 6 },
{ "UserMessage": "Good Morning", "UserLikes": 12 },
{ "UserMessage": "Awesome", "UserLikes": 4 }
]
});
Method 1: Using Projection (Returns All Array Elements)
db.queryToEmbeddedDocument.find(
{ "PostDetails.UserLikes": { $gte: 8 } },
{ PostDetails: 1 }
);
{
"_id": ObjectId("5c988a9f330fd0aa0d2fe4bd"),
"PostDetails": [
{ "UserMessage": "Hello", "UserLikes": 8 },
{ "UserMessage": "Hi", "UserLikes": 6 },
{ "UserMessage": "Good Morning", "UserLikes": 12 },
{ "UserMessage": "Awesome", "UserLikes": 4 }
]
}
Method 2: Using $elemMatch (Returns Only Matching Elements)
db.queryToEmbeddedDocument.find(
{ "PostDetails.UserLikes": { $gte: 8 } },
{ "PostDetails": { $elemMatch: { "UserLikes": { $gte: 8 } } } }
);
{
"_id": ObjectId("5c988a9f330fd0aa0d2fe4bd"),
"PostDetails": [
{ "UserMessage": "Hello", "UserLikes": 8 }
]
}
Method 3: Using Aggregation Pipeline
db.queryToEmbeddedDocument.aggregate([
{ $match: { "PostDetails.UserLikes": { $gte: 8 } } },
{ $unwind: "$PostDetails" },
{ $match: { "PostDetails.UserLikes": { $gte: 8 } } },
{ $project: { "PostDetails": 1 } }
]);
{ "_id": ObjectId("..."), "PostDetails": { "UserMessage": "Hello", "UserLikes": 8 } }
{ "_id": ObjectId("..."), "PostDetails": { "UserMessage": "Good Morning", "UserLikes": 12 } }
Key Differences
- Projection alone returns the entire array even if only some elements match
- $elemMatch returns only the first matching array element
- Aggregation returns all matching elements as separate documents
Conclusion
Use $elemMatch in projection to return only the first matching embedded document, or use aggregation with $unwind to get all matching elements as separate results.
Advertisements
