Tutorialspoint

1 Answer
Smita Kapse

To fund a value from JSON data, use the find() along with dot(.) notation. Let us first create a collection with documents −

> db.findValueFromJsonDemo.insertOne(
   {
      "UserDetails": [{
         "_id": new ObjectId(),
         "UserName": "Carol",
         "UserMessage": "Hi"
      }],
      "UserFriendsName": ["John","Sam"]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdf8a4cbf3115999ed511fd")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cdf8a4cbf3115999ed511fd"),
   "UserDetails" : [
      {
         "_id" : ObjectId("5cdf8a4cbf3115999ed511fc"),
         "UserName" : "Carol",
         "UserMessage" : "Hi"
      }
   ],
   "UserFriendsName" : [
      "John",
      "Sam"
   ]
}

Following is the query to find a value from json data −

> db.findValueFromJsonDemo.find({'UserDetails.UserMessage': "Hi"});

This will produce the following output −

{
   "_id" : ObjectId("5cdf8a4cbf3115999ed511fd"),
   "UserDetails" : [
      {
         "_id" : ObjectId("5cdf8a4cbf3115999ed511fc"), "UserName" : "Carol", "UserMessage" : "Hi"
      }
   ],
   "UserFriendsName" : [
      "John", "Sam"
   ]
}

Advertisements

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