 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do you find a MongoDB record that is two level deep?
To find a MongoDB record that is two level deep, loop inside MongoDB $where. Let us create a collection with documents −
> db.demo468.insertOne( ... { ... "_id" : new ObjectId(), ... "FirstPosition" : { ...    "StudentName" : "Chris", ...    "StudentAge" : 23 ... }, ... "SecondPosition" : { ...    "StudentName" : "David", ...    "StudentAge" : 20 ... } ... } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5e804e2fb0f3fa88e2279069") } > db.demo468.insertOne( ... { ... "_id" : new ObjectId(), ... "FirstPosition" : { ...    "StudentName" : "Carol", ...    "StudentAge" : 21 ... }, ... "SecondPosition" : { ...    "StudentName" : "John", ...    "StudentAge" : 22 ... } ... } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5e804fb0b0f3fa88e227906a") } Display all documents from a collection with the help of find() method −
> db.demo468.find();
This will produce the following output −
{ "_id" : ObjectId("5e804e2fb0f3fa88e2279069"), "FirstPosition" : { "StudentName" : "Chris", "StudentAge" : 23 }, "SecondPosition" : { "StudentName" : "David", "StudentAge" : 20 } } { "_id" : ObjectId("5e804fb0b0f3fa88e227906a"), "FirstPosition" : { "StudentName" : "Carol", "StudentAge" : 21 }, "SecondPosition" : { "StudentName" : "John", "StudentAge" : 22 } } Following is the query to find a MongoDB record that is two level deep −
> db.demo468.find({ ... $where: function() { ...    for (var i in this) { ...       if (this[i]["StudentName"] == "John") { ...          return true; ...       } ...    } ...    return false; ... } ... }) This will produce the following output −
{ "_id" : ObjectId("5e804fb0b0f3fa88e227906a"), "FirstPosition" : { "StudentName" : "Carol", "StudentAge" : 21 }, "SecondPosition" : { "StudentName" : "John", "StudentAge" : 22 } }Advertisements
 