Filtering MongoDB items by fields and subfields?


To filter items by fields and subfields, use dot notation. Let us create a collection with documents −

> db.demo638.insert({Name:"Chris"});
WriteResult({ "nInserted" : 1 })
> db.demo638.insert({Name:"David",details:{Subject:"MongoDB"}});
WriteResult({ "nInserted" : 1 })

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

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

This will produce the following output −

{ "_id" : ObjectId("5e9c28666c954c74be91e6de"), "Name" : "Chris" }
   {
      "_id" : ObjectId("5e9c28866c954c74be91e6df"),
      "Name" : "David",
      "details" : {
         "Subject" : "MongoDB"
   }
}

Following is the query to filter items by multiple fields and subfields −

> db.demo638.find({"details.Subject":null});

This will produce the following output −

{ "_id" : ObjectId("5e9c28666c954c74be91e6de"), "Name" : "Chris" }

Updated on: 12-May-2020

389 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements