Tutorialspoint

1 Answer
Arjun Thakur

Let us first create a collection with documents −

> db.findDataDemo.insertOne(
   {
      "_id": new ObjectId(),
      "CustomerName":"John",
      "CustomerDetails" : {
         "CountryName" : [
            "AUS"
         ],
         "isMarried" : [
            false
         ]
      }
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefa5eeef71edecf6a1f6a5")
}
> db.findDataDemo.insertOne(
   {
      "_id": new ObjectId(),
      "CustomerName":"Carol",
      "CustomerDetails" : {
         "CountryName" : [
            "UK"
         ],
         "isMarried" : [
            true
         ]
      }
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefa60aef71edecf6a1f6a6")
}

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

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

Output

{
   "_id" : ObjectId("5cefa5eeef71edecf6a1f6a5"),
   "CustomerName" : "John",
   "CustomerDetails" : {
      "CountryName" : [
         "AUS"
      ],
      "isMarried" : [
         false
      ]
   }
}
{
   "_id" : ObjectId("5cefa60aef71edecf6a1f6a6"),
   "CustomerName" : "Carol",
   "CustomerDetails" : {
      "CountryName" : [
         "UK"
      ],
      "isMarried" : [
         true
      ]
   }
}

Following is the query to find data from an array inside an object −

> db.findDataDemo.find({"CustomerDetails.CountryName":"UK"});

Output

{ "_id" : ObjectId("5cefa60aef71edecf6a1f6a6"), "CustomerName" : "Carol", "CustomerDetails" : { "CountryName" : [ "UK" ], "isMarried" : [ true ] } }

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.