Use mongodb $nin and $in operator with field value

Viewed 208

Is it possible to use the $in and $nin Operator in an aggregation with the value from a field or a variable from a pipeline? I have an Array of objectId's as pipeline variable and would like to get all documents except these ids. Is there a workaround or another approach to achieve this?

1 Answers

You can use $addFields to project a helper field for filtering. Then, do a $match on the helper field.

db.collection.aggregate([
  {
    "$addFields": {
      "isValid": {
        "$in": [
          "$_id",
          [
            ObjectId("5a934e000102030405000000"),
            ObjectId("5a934e000102030405000001")
          ]
        ]
      }
    }
  },
  {
    $match: {
      isValid: false
    }
  }
])

Here is the Mongo playground for your reference

Related