- 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
MongoDB, finding all documents where property id equals to record id?
For this, use $where and compare with ==. Let us create a collection with documents −
> db.demo69.insertOne( ... { ... "_id" : ObjectId("507c7f79bcf86cd7994f6c0e"), ... "Details" : { ... ... "id" : ObjectId("507c7f79bcf86cd7994f6c0e") ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("507c7f79bcf86cd7994f6c0e") } > db.demo69.insertOne( ... { ... "_id" : ObjectId("507c7f79bcf86cd7994f6c0f"), "Details" : { ... "id" :ObjectId("507c7f79bcf86cd7994f6c0a") ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("507c7f79bcf86cd7994f6c0f") }
Display all documents from a collection with the help of find() method −
> db.demo69.find();
This will produce the following output −
{ "_id" : ObjectId("507c7f79bcf86cd7994f6c0e"), "Details" : { "id" : ObjectId("507c7f79bcf86cd7994f6c0e") } } { "_id" : ObjectId("507c7f79bcf86cd7994f6c0f"), "Details" : { "id" : ObjectId("507c7f79bcf86cd7994f6c0a") } }
Following is the query to find all documents where property id equals to record id −
> db.demo69.find({ ... $where: function(){ ... return this._id.toString() == this.Details.id.toString(); ... } ... }).pretty();
This will produce the following output −
{ "_id" : ObjectId("507c7f79bcf86cd7994f6c0e"), "Details" : { "id" : ObjectId("507c7f79bcf86cd7994f6c0e") } }
Advertisements