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
Check for existing documents/embedded documents in MongoDB
To check for existing documents or embedded documents in MongoDB, use the $exists operator. This operator matches documents where a specified field exists, regardless of its value.
Syntax
db.collection.find({ "fieldName": { $exists: true } })
db.collection.find({ "embeddedField.subField": { $exists: true } })
Sample Data
Let us create a collection with documents containing embedded arrays ?
db.demo322.insertMany([
{
"id": 1001,
"details": [
{ "Score": 10000, "Name": "Bob" },
{ "Score": 98000, "Name": "Sam" }
]
},
{
"id": 10002,
"details": [
{ "Score": 9000 },
{ "Score": 91000 }
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e5113e2f8647eb59e56206c"),
ObjectId("5e5113faf8647eb59e56206d")
]
}
Display all documents from the collection ?
db.demo322.find();
{
"_id": ObjectId("5e5113e2f8647eb59e56206c"),
"id": 1001,
"details": [
{ "Score": 10000, "Name": "Bob" },
{ "Score": 98000, "Name": "Sam" }
]
}
{
"_id": ObjectId("5e5113faf8647eb59e56206d"),
"id": 10002,
"details": [
{ "Score": 9000 },
{ "Score": 91000 }
]
}
Example: Check for Embedded Field Existence
Check if any documents contain the "Name" field within the "details" array ?
db.demo322.find({ "details.Name": { $exists: true } }).count() > 0;
true
This returns true because the first document has "Name" fields in its details array.
Key Points
-
$exists: truematches documents where the field exists -
$exists: falsematches documents where the field does not exist - Use dot notation to check embedded fields in arrays or subdocuments
- Combine with
.count()to verify existence of matching documents
Conclusion
The $exists operator is essential for checking field presence in MongoDB documents. Use dot notation to target embedded fields within arrays or subdocuments for precise field existence validation.
Advertisements
