Loudrous
Loudrous

Reputation: 1305

Check if an array contains another fields value

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?

Upvotes: 0

Views: 1618

Answers (1)

Takis
Takis

Reputation: 8705

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"]}]}}}])

Upvotes: 2

Related Questions