Find documents that contains specific field in MongoDB?


For this, use the $exists operator. Let us first create a collection with documents −

>dbfindDocumentContainsSpecificFieldDemoinsertOne({"ProductPrices":{"Product1":10,"Pr oduct2":50}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cf2385bb64a577be5a2bc14")
}
>dbfindDocumentContainsSpecificFieldDemoinsertOne({"ProductPrices":{"Product3":150,"P roduct7":100,"Product5":250}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cf2387eb64a577be5a2bc15")
}

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

> dbfindDocumentContainsSpecificFieldDemofind()pretty();

This will produce the following document −

{
   "_id" : ObjectId("5cf2385bb64a577be5a2bc14"),
   "ProductPrices" : {
      "Product1" : 10,
      "Product2" : 50
   }
}
{
   "_id" : ObjectId("5cf2387eb64a577be5a2bc15"),
   "ProductPrices" : {
      "Product3" : 150,
      "Product7" : 100,
      "Product5" : 250
   }
}

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

> dbfindDocumentContainsSpecificFieldDemofind({"ProductPricesProduct2":{$exists:true}});

This will produce the following document −

{ "_id" : ObjectId("5cf2385bb64a577be5a2bc14"), "ProductPrices" : { "Product1" : 10, "Product2" : 50 } }
raja
Published on 14-Jun-2019 14:49:58
Advertisements