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
Field selection within MongoDB query using dot notation?
Field selection in MongoDB using dot notation allows you to access and filter nested fields within embedded documents or arrays. Use dot notation to specify which fields to include or exclude in query results.
Syntax
db.collection.find(
{"parentField.nestedField": "value"},
{"parentField.specificField": 1/0}
);
Sample Data
db.demo302.insertMany([
{"Id": 101, "details": [{"Name": "Chris", "Age": 21, "Subject": "MySQL"}]},
{"Id": 102, "details": [{"Name": "Bob", "Age": 23, "Subject": "MongoDB"}]},
{"Id": 103, "details": [{"Name": "David", "Age": 20, "Subject": "Java"}]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e4d746f5d93261e4bc9ea52"),
ObjectId("5e4d74815d93261e4bc9ea53"),
ObjectId("5e4d74955d93261e4bc9ea54")
]
}
Display All Documents
db.demo302.find();
{ "_id" : ObjectId("5e4d746f5d93261e4bc9ea52"), "Id" : 101, "details" : [ { "Name" : "Chris", "Age" : 21, "Subject" : "MySQL" } ] }
{ "_id" : ObjectId("5e4d74815d93261e4bc9ea53"), "Id" : 102, "details" : [ { "Name" : "Bob", "Age" : 23, "Subject" : "MongoDB" } ] }
{ "_id" : ObjectId("5e4d74955d93261e4bc9ea54"), "Id" : 103, "details" : [ { "Name" : "David", "Age" : 20, "Subject" : "Java" } ] }
Example: Field Selection Using Dot Notation
Query documents where Subject is "MongoDB" and exclude Name, Age, _id, and Id fields ?
db.demo302.find(
{"details.Subject": "MongoDB"},
{"details.Name": 0, "details.Age": 0, "_id": 0, "Id": 0}
);
{ "details" : [ { "Subject" : "MongoDB" } ] }
Key Points
- Use
parentField.nestedFieldsyntax to access nested fields in arrays or embedded documents. - Field projection:
1includes the field,0excludes it. - Dot notation works for both query conditions and field selection.
Conclusion
Dot notation enables precise field selection within nested MongoDB documents. Combine it with projection operators to control which nested fields appear in query results, making data retrieval more efficient and focused.
Advertisements
