![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" } }
Advertisements