Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Insert MongoDB document field only when it's missing?
Let us first create a collection with documents −
>db.missingDocumentDemo.insertOne({"StudentFirstName":"Adam","StudentLastName":"Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd3fb1eedc6604c74817ce6")
}
>db.missingDocumentDemo.insertOne({"StudentFirstName":"Carol","StudentLastName":"Taylor"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd3fb29edc6604c74817ce7")
}
>db.missingDocumentDemo.insertOne({"StudentFirstName":"David","StudentLastName":"Miller","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd3fb40edc6604c74817ce8")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.missingDocumentDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd3fb1eedc6604c74817ce6"),
"StudentFirstName" : "Adam",
"StudentLastName" : "Smith"
}
{
"_id" : ObjectId("5cd3fb29edc6604c74817ce7"),
"StudentFirstName" : "Carol",
"StudentLastName" : "Taylor"
}
{
"_id" : ObjectId("5cd3fb40edc6604c74817ce8"),
"StudentFirstName" : "David",
"StudentLastName" : "Miller",
"StudentAge" : 21
}
Here is the query to insert MongoDB document field only when it's missing. We are trying to insert StudentAge field here. It won’t insert the field if it already exist −
> db.missingDocumentDemo.update(
... { "StudentAge": { "$exists": false } },
... { "$set": { "StudentAge": 23 } },
... { "multi": true }
... );
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
Let us display all the documents from the above collection −
> db.missingDocumentDemo.find().pretty();
This will produce the following output −
{
"_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
}Advertisements