skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search