Find MongoDB documents that contains specific field?

MongoDBDatabaseBig Data Analytics

To find documents that contain specific field, use $exists. Let us create a collection with documents −

> db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"Chris","ClientAge":34}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46b2a31627c0c63e7dba69")
}
>db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"John","ClientLastName":"Smith","ClientAge":31}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46b2be1627c0c63e7dba6a")
}
> db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"David","ClientAge":33}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46b2cd1627c0c63e7dba6b")
}
>db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"David","ClientLastName":"Miller","ClientAge":31}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46b2de1627c0c63e7dba6c")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e46b2a31627c0c63e7dba69"),
   "ClientDetails" : [
      {
         "ClientFirstName" : "Chris",
         "ClientAge" : 34
      }
   ]
}
{
   "_id" : ObjectId("5e46b2be1627c0c63e7dba6a"),
   "ClientDetails" : [
      {
         "ClientFirstName" : "John",
         "ClientLastName" : "Smith",
         "ClientAge" : 31
      }
   ]
}
{
   "_id" : ObjectId("5e46b2cd1627c0c63e7dba6b"),
   "ClientDetails" : [
      {
         "ClientFirstName" : "David",
         "ClientAge" : 33
      }
   ]
}
{
   "_id" : ObjectId("5e46b2de1627c0c63e7dba6c"),
   "ClientDetails" : [
      {
         "ClientFirstName" : "David",
         "ClientLastName" : "Miller",
         "ClientAge" : 31
      }
   ]
}

Following is the query to find documents that contains specific field −

> db.demo247.find({"ClientDetails.ClientLastName":{$exists:true}});

This will produce the following output −

{
   "_id" : ObjectId("5e46b2be1627c0c63e7dba6a"), "ClientDetails" : [
      { "ClientFirstName" : "John", "ClientLastName" : "Smith", "ClientAge" : 31 }
   ]
}
{
   "_id" : ObjectId("5e46b2de1627c0c63e7dba6c"), "ClientDetails" : [
      { "ClientFirstName" : "David", "ClientLastName" : "Miller", "ClientAge" : 31 }
   ] 
}
raja
Published on 30-Mar-2020 17:36:23
Advertisements