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
Insert MongoDB document field only when it's missing?
To insert a MongoDB document field only when it's missing, use the $exists operator in the query condition to target documents where the field doesn't exist, then apply $set to add the field only to those documents.
Syntax
db.collection.update(
{ "fieldName": { "$exists": false } },
{ "$set": { "fieldName": "value" } },
{ "multi": true }
);
Sample Data
db.missingDocumentDemo.insertMany([
{"StudentFirstName": "Adam", "StudentLastName": "Smith"},
{"StudentFirstName": "Carol", "StudentLastName": "Taylor"},
{"StudentFirstName": "David", "StudentLastName": "Miller", "StudentAge": 21}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd3fb1eedc6604c74817ce6"),
ObjectId("5cd3fb29edc6604c74817ce7"),
ObjectId("5cd3fb40edc6604c74817ce8")
]
}
Initial Documents
db.missingDocumentDemo.find();
{
"_id": ObjectId("5cd3fb1eedc6604c74817ce6"),
"StudentFirstName": "Adam",
"StudentLastName": "Smith"
}
{
"_id": ObjectId("5cd3fb29edc6604c74817ce7"),
"StudentFirstName": "Carol",
"StudentLastName": "Taylor"
}
{
"_id": ObjectId("5cd3fb40edc6604c74817ce8"),
"StudentFirstName": "David",
"StudentLastName": "Miller",
"StudentAge": 21
}
Example: Add Missing StudentAge Field
Add StudentAge field only to documents that don't already have it ?
db.missingDocumentDemo.update(
{ "StudentAge": { "$exists": false } },
{ "$set": { "StudentAge": 23 } },
{ "multi": true }
);
WriteResult({ "nMatched": 2, "nUpserted": 0, "nModified": 2 })
Verify Results
db.missingDocumentDemo.find();
{
"_id": ObjectId("5cd3fb1eedc6604c74817ce6"),
"StudentFirstName": "Adam",
"StudentLastName": "Smith",
"StudentAge": 23
}
{
"_id": ObjectId("5cd3fb29edc6604c74817ce7"),
"StudentFirstName": "Carol",
"StudentLastName": "Taylor",
"StudentAge": 23
}
{
"_id": ObjectId("5cd3fb40edc6604c74817ce8"),
"StudentFirstName": "David",
"StudentLastName": "Miller",
"StudentAge": 21
}
Key Points
-
{"fieldName": {"$exists": false}}matches documents missing the specified field. -
{"multi": true}ensures all matching documents are updated, not just the first one. - Existing field values remain unchanged when the field already exists.
Conclusion
Use $exists: false to selectively add fields only to documents that lack them. This approach preserves existing data while filling gaps in your document structure efficiently.
Advertisements
