How to select MongoDB document that does not consist a specific field?

MongoDBDatabaseBig Data Analytics

Check for a specific field using MongoDB $exists. If that field does not exist in a document, then you need to display the same document with find().

Let us create a collection with documents −

> db.demo612.insertOne({id:1,"Info":[{Name:"Chris",Age:21},{Name:"David"}]});{
   "acknowledged" : true, "insertedId" : ObjectId("5e987372f6b89257f5584d87")
}

Display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5e987372f6b89257f5584d87"),
   "id" : 1,
   "Info" : [
      {
         "Name" : "Chris",
         "Age" : 21
      },
      {
         "Name" : "David"
      }
   ]
}

Following is the query to fetch a MongoDB document that does not consist of a specific field −

> db.demo612.aggregate({$unwind: "$Info"},
... {$match: {"Info.Age":{$exists: false}}},
... {$project: {"Info.Name": 1}})

This will produce the following output −

{ "_id" : ObjectId("5e987372f6b89257f5584d87"), "Info" : { "Name" : "David" } }
raja
Published on 15-May-2020 11:38:37
Advertisements