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
Get all embedded documents with "isMarried" status in a MongoDB collection
To get all embedded documents with specific fields in MongoDB, use the $project aggregation operator. This allows you to extract and display specific fields from embedded documents.
Syntax
db.collection.aggregate([
{
$project: {
"fieldName": "$embeddedDocument.fieldName",
"anotherField": "$embeddedDocument.anotherField"
}
}
]);
Sample Data
db.demo220.insertMany([
{
"id": 101,
"FullName": "John Doe",
"EmailId": "john12@gmail.com",
"ShippingDate": new ISODate(),
"details": { "_id": 1001, "isMarried": true }
},
{
"id": 102,
"FullName": "John Smith",
"EmailId": "johnsmith@gmail.com",
"ShippingDate": new ISODate(),
"details": { "_id": 1002, "isMarried": false }
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e3eaf5b03d395bdc213471d"),
ObjectId("5e3eaf5c03d395bdc213471e")
]
}
Display All Documents
db.demo220.find();
{ "_id": ObjectId("5e3eaf5b03d395bdc213471d"), "id": 101, "FullName": "John Doe", "EmailId": "john12@gmail.com", "ShippingDate": ISODate("2020-02-08T12:53:47.876Z"), "details": { "_id": 1001, "isMarried": true } }
{ "_id": ObjectId("5e3eaf5c03d395bdc213471e"), "id": 102, "FullName": "John Smith", "EmailId": "johnsmith@gmail.com", "ShippingDate": ISODate("2020-02-08T12:53:48.991Z"), "details": { "_id": 1002, "isMarried": false } }
Extract Embedded Document Fields
Use $project to extract the "isMarried" status from the embedded "details" document ?
db.demo220.aggregate([
{
$project: {
"isMarried": "$details.isMarried",
"detailsId": "$details._id"
}
}
]);
{ "_id": ObjectId("5e3eaf5b03d395bdc213471d"), "isMarried": true, "detailsId": 1001 }
{ "_id": ObjectId("5e3eaf5c03d395bdc213471e"), "isMarried": false, "detailsId": 1002 }
Key Points
- Use dot notation with
$prefix to access embedded document fields:"$details.isMarried" -
$projectcreates new fields in the output while maintaining the original_id - You can extract multiple fields from the same embedded document in one projection
Conclusion
The $project aggregation operator efficiently extracts specific fields from embedded documents using dot notation. This approach provides clean, focused results containing only the required embedded data.
Advertisements
