Home > database >  check if array includes element in mongodb aggregation
check if array includes element in mongodb aggregation

Time:11-28

I have one collection of documents that are formatted as follows:

{
  _id: ObjectId('617d318eb863ee273c66b111'),
  my_object: {
    _id: ObjectId('617d318eb863ee273c66b222')
    //other fields
  },
  exclusion_object: {
    my_arr: ObjectId('617d318eb863ee273c66b222')
    //other fields
  }
}

So I need to exclude the documents where my_object._id is included in exclusion_object.my_arr

I tried (in $match stage):

{
  $match:{
    'exclusion_object.my_arr': { $nin:['my_object._id','$exclusion_object.my_arr']}
  }
}

This doesn't seem to work.. any suggestion?

CodePudding user response:

Query

  • $in query operator needs value so we cant use it with $fieldName
    { field: { $in: [<value1>, <value2>, ... <valueN> ] } }
  • $in aggregate operator takes expression also so we can use it with $fieldName
    { $in: [ <expression>, <array expression> ] }
  • when aggregate operator is used on $match $expr operator is needed also

Test code here

aggregate(
[{"$match": 
   {"$expr": 
     {"$not": [{"$in": ["$my_object._id", "$exclusion_object.my_arr"]}]}}}])
  • Related