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



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" } }
Updated on: 2020-05-15T08:09:00+05:30

277 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements