Search a value in an object with number keys with MongoDB


To search a value, simply use $where in MongoDB. Let us create a collection with documents −

> db.demo268.insertOne(
...   {
...      "details" : {
...         "101" : "John",
...         "1001" : "Bob"
...      }
...   }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4816141627c0c63e7dbaaf")
}

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

> db.demo268.find();

This will produce the following output −

{ "_id" : ObjectId("5e4816141627c0c63e7dbaaf"), "details" : { "101" : "John", "1001" : "Bob" } }

Following is the query to search a value in an object with number keys −

> db.demo268.find({ $where:
...   function() {
...      for (var k in this.details) {
...         if (this.details[k] == "Bob") {
...            return true;
...         }
...      }
...   }
...})

This will produce the following output −

{ "_id" : ObjectId("5e4816141627c0c63e7dbaaf"), "details" : { "101" : "John", "1001" : "Bob" } }

Updated on: 31-Mar-2020

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements