MongoDB, finding all documents where property id equals to record id?

MongoDBDatabaseBig Data Analytics

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")
   }
}
raja
Published on 30-Mar-2020 07:33:44
Advertisements