Loudrous
Loudrous

Reputation: 1305

How to check if an array has the same elements as another one in mongodb aggregation

I need to match all documents where field arr, which is an array of object Ids, has same elements of a given one no matther the position.

I tried:

[
  {
    $match:{
      arr: givenArr
    }
  }
]

or

[
  {
    $match:{
      arr: {
          $in: givenArr
        }
    }
  }
]

The first pipeline matches all the documents that have same elements in the same position.

The second pipeline matches all the documents that has at least one element in the given array.

For example if I have a couple of documents like:

[
  {
    _id: ObjectId("639a0e4cc0f6595d90a84de4"),
    arr: [
      ObjectId("639a0e4cc0f6595d90a84de1"),
      ObjectId("639a0e4cc0f6595d90a84de2"),
      ObjectId("639a0e4cc0f6595d90a84de3"),
    ]
  },
  {
    _id: ObjectId("639a0e4cc0f6595d90a84de5"),
    arr: [
      ObjectId("639a0e4cc0f6595d90a84de7"),
      ObjectId("639a0e4cc0f6595d90a84de8"),
      ObjectId("639a0e4cc0f6595d90a84de9"),
    ]
  },
]

If I need to match all of those documents that have arr same as

[
  ObjectId("639a0e4cc0f6595d90a84de8"),
  ObjectId("639a0e4cc0f6595d90a84de9"),
  ObjectId("639a0e4cc0f6595d90a84de7"),
]

I want to get only the second document.

How could I do that?

Upvotes: 0

Views: 186

Answers (2)

rickhg12hs
rickhg12hs

Reputation: 11942

You could treat each array as a set and use "$setEquals".

db.collection.find({
  $expr: {
    $setEquals: [
      "$arr",
      [
        ObjectId("639a0e4cc0f6595d90a84de8"),
        ObjectId("639a0e4cc0f6595d90a84de9"),
        ObjectId("639a0e4cc0f6595d90a84de7")
      ]
    ]
  }
})

Try it on mongoplayground.net.

Upvotes: 3

ray
ray

Reputation: 15286

You can compare the sorted results of your 2 arrays computed by $sortArray

db.collection.find({
  $expr: {
    $eq: [
      {
        $sortArray: {
          input: "$arr",
          sortBy: 1
        }
      },
      {
        $sortArray: {
          input: [
            ObjectId("639a0e4cc0f6595d90a84de8"),
            ObjectId("639a0e4cc0f6595d90a84de9"),
            ObjectId("639a0e4cc0f6595d90a84de7"),
            
          ],
          sortBy: 1
        }
      }
    ]
  }
})

Mongo Playground

Upvotes: 2

Related Questions