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
Filtering MongoDB items by fields and subfields?
To filter MongoDB documents by fields and subfields, use dot notation to access nested properties. This allows you to query specific values within embedded documents or check for field existence.
Syntax
db.collection.find({"field.subfield": value});
db.collection.find({"field.subfield": null});
db.collection.find({"field.subfield": {$exists: true}});
Sample Data
db.demo638.insertMany([
{Name: "Chris"},
{Name: "David", details: {Subject: "MongoDB"}},
{Name: "John", details: {Subject: "JavaScript", Level: "Advanced"}}
]);
WriteResult({ "nInserted" : 3 })
Display all documents from the collection ?
db.demo638.find().pretty();
{
"_id" : ObjectId("5e9c28666c954c74be91e6de"),
"Name" : "Chris"
}
{
"_id" : ObjectId("5e9c28866c954c74be91e6df"),
"Name" : "David",
"details" : {
"Subject" : "MongoDB"
}
}
{
"_id" : ObjectId("5e9c28966c954c74be91e6e0"),
"Name" : "John",
"details" : {
"Subject" : "JavaScript",
"Level" : "Advanced"
}
}
Example 1: Filter by Missing Subfield
Find documents where the subfield doesn't exist or is null ?
db.demo638.find({"details.Subject": null});
{ "_id" : ObjectId("5e9c28666c954c74be91e6de"), "Name" : "Chris" }
Example 2: Filter by Specific Subfield Value
Find documents with a specific subject ?
db.demo638.find({"details.Subject": "MongoDB"});
{
"_id" : ObjectId("5e9c28866c954c74be91e6df"),
"Name" : "David",
"details" : {
"Subject" : "MongoDB"
}
}
Example 3: Multiple Subfield Conditions
Filter by multiple nested fields simultaneously ?
db.demo638.find({
"details.Subject": "JavaScript",
"details.Level": "Advanced"
});
{
"_id" : ObjectId("5e9c28966c954c74be91e6e0"),
"Name" : "John",
"details" : {
"Subject" : "JavaScript",
"Level" : "Advanced"
}
}
Key Points
- Use dot notation to access nested fields:
"field.subfield" - Querying with
nullmatches documents where the field doesn't exist or has null value - Multiple subfield conditions are combined with AND logic by default
Conclusion
Dot notation enables precise filtering of MongoDB documents by nested fields. Use quotes around the field path and combine multiple conditions to create targeted queries for embedded document properties.
Advertisements
