MongoDB query to find a value from JSON like data?


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"
   ]
}

Updated on: 30-Jul-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements