Check if value exists for a field in a MongoDB document?



To check if value exists for a field in a MongoDB document, you can use find() along with $exists operator. Let us first create a collection with documents −

> db.checkIfValueDemo.insertOne({"PlayerName":"John Smith","PlayerScores":[5000,98595858,554343]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cc6f507af8e7a4ca6b2ad98") } > db.checkIfValueDemo.insertOne({"PlayerName":"John Doe","PlayerScores":[]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cc6f512af8e7a4ca6b2ad99") } > db.checkIfValueDemo.insertOne({"PlayerName":"Carol Taylor","PlayerScores":[7848474,8746345353]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cc6f521af8e7a4ca6b2ad9a") } > db.checkIfValueDemo.insertOne({"PlayerName":"David Miller","PlayerScores":[]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cc6f531af8e7a4ca6b2ad9b") }

Following is the query to display all documents from a collection with the help of find() method −

> db.checkIfValueDemo.find().pretty();

This will produce the following output −

{    "_id" : ObjectId("5cc6f507af8e7a4ca6b2ad98"),    "PlayerName" : "John Smith",    "PlayerScores" : [       5000,       98595858,       554343    ] } {    "_id" : ObjectId("5cc6f512af8e7a4ca6b2ad99"),    "PlayerName" : "John Doe",    "PlayerScores" : [ ] } {    "_id" : ObjectId("5cc6f521af8e7a4ca6b2ad9a"),    "PlayerName" : "Carol Taylor",    "PlayerScores" : [       7848474,       8746345353    ] } {    "_id" : ObjectId("5cc6f531af8e7a4ca6b2ad9b"),    "PlayerName" : "David Miller",    "PlayerScores" : [ ] }

Following is the query to check if value exists for a field in a document. Here, we are checking for field 'PlayerScores with value [ ] −

> db.checkIfValueDemo.find({'PlayerScores.0' : {$exists: true}}).count();

This will produce the following output

2
Updated on: 2019-07-30T22:30:26+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements