0

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

For those who needs $setEquals works also in $project pipeline with aggregation framework. GG @rickhg12hs
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.