Home > OS >  MongoDB: find field value in other field values
MongoDB: find field value in other field values

Time:10-06

I have a document in following format

{
"selectedIds":[1, 2, 3],
"currentId": 1 
}

I want to write a mongo query to find if currentId is present in selectedIds. I tried with following query, however, it states that $in needs an array

{
   '$match': {
        'selectedIds': {'$exists': True}, 
        'currentId': {'$in': '$selectedIds'}
        }        
}

Please help with the query

CodePudding user response:

You can use $expr into $match like this:

db.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$in": [
          "$currentId",
          "$selectedIds"
        ]
      }
    }
  }
])

Example here

CodePudding user response:

you can get ObjectId of those by this query

db.collection.aggregate([{"$unwind":"$selectedIds"},{$match:{$expr:{$eq:["$selectedIds","$currentId"]}}},{$group:{_id:"$_id"}}])
  • Related