Home > Mobile >  How to match two different Object ids using MongoDB find() query?
How to match two different Object ids using MongoDB find() query?

Time:09-21

I have an entry like below,

[
  {
    "_id":ObjectId("59ce020caa87df4da0ee2c78"),
    "name": "Tom",
    "owner_id": ObjectId("59ce020caa87df4da0ee2c78")
  },
  {
    "_id":ObjectId("59ce020caa87df4da0ee2c79"),
    "name": "John",
    "owner_id": ObjectId("59ce020caa87df4da0ee2c78")
  }
]

now, I need to find the person whose _id is equal to owner_id using find() in MongoDB. Note, we can't not use $match (aggregation) due to some reason.

I am using this query,

db.people.find({ $where:  "this._id == this.owner_id" })

but, it's not returning the expected output. Can anyone help me with this.

Thanks.

CodePudding user response:

Using $expr and $eq you can get desired values avoiding the use of $where into a find stage (not aggregation necessary).

db.collection.find({
  "$expr": {
    "$eq": [
      "$_id",
      "$owner_id"
    ]
  }
})
  • Related