Tutorialspoint

1 Answer
Smita Kapse

To retrieve array values, use dot(.) notation. Let us first create a collection with documents −

> db.retrievingArrayDemo.insertOne(
   { "UserDetails" : [
      { "UserName" : "John", "UserAge" : 23 } ],
      "UserCountryName" : "AUS",
      "UserLoginDate" : new ISODate(),
      "UserMessage" : "Hello"
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce9718478f00858fb12e920")
}
> db.retrievingArrayDemo.insertOne(
   { "UserDetails" : [
      { "UserName" : "Sam", "UserAge" : 24 } ],
      "UserCountryName" : "UK",
      "UserLoginDate" : new ISODate(),
      "UserMessage" : "Bye"
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce9718478f00858fb12e921")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5ce9718478f00858fb12e920"),
   "UserDetails" : [
      {
         "UserName" : "John",
         "UserAge" : 23
      }
   ],
   "UserCountryName" : "AUS",
   "UserLoginDate" : ISODate("2019-05-25T16:47:00.211Z"),
   "UserMessage" : "Hello"
}
{
   "_id" : ObjectId("5ce9718478f00858fb12e921"),
   "UserDetails" : [
      {
         "UserName" : "Sam",
         "UserAge" : 24
      }
   ],
   "UserCountryName" : "UK",
   "UserLoginDate" : ISODate("2019-05-25T16:47:00.670Z"),
   "UserMessage" : "Bye"
}

Following is the query to retrieve array values from a find query −

> db.retrievingArrayDemo.find({"UserCountryName" : "UK", "UserDetails.UserName":"Sam"}).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5ce9718478f00858fb12e921"),
   "UserDetails" : [
      {
         "UserName" : "Sam",
         "UserAge" : 24
      }
   ],
   "UserCountryName" : "UK",
   "UserLoginDate" : ISODate("2019-05-25T16:47:00.670Z"),
   "UserMessage" : "Bye"
}

Advertisements

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