MongoDB - Find documents whose multiple fields are not present in another collection

Viewed 728

I have MongoDB database and I am trying to return those documents that do not have more than one field in another collection/array. Example data I want filter:

[
  {
    id: "1",
    version: "1",
    data: "test"
  },
  {
    id: "2",
    version: "3",
    data: "test"
  },
  {
    id: "3",
    version: "2",
    data: "test"
  }
]

I need to get those that are not present in an array like this:

[
  {
    id: "2",
    version: "2",
  },
  {
    id: "3",
    version: "2",
  }
]

For this example it should return documents:

  • id: 1 - id not present in filter array at all
  • id: 2 - id is present but "version" field does not match

Use case is to return documents that were not shown in current version. I tried to use $nin but that only supports a collection of values to filter single field. If I use it in $and operator it compares it independently. I also setup a simple playground: MongoDB playground

1 Answers

You can use $nor operator, performs a logical NOR operation on an array of one or more query expression and selects the documents that fail all the query expressions in the array.

db.collection.find({
  $nor: [
    {
      id: "2",
      version: "2"
    },
    {
      id: "3",
      version: "2"
    }
  ]
})

Playground

Related