Search a value in an object with number keys with MongoDB

MongoDBDatabaseBig Data Analytics

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" } }
raja
Published on 31-Mar-2020 12:14:18
Advertisements