Yash
Yash

Reputation: 308

How to form a exact query for finding id's inside array

I've a document like this:

{
    "_id" : ObjectId("xxx"),
    "users" : [ 
        {
            "_id" : ObjectId("xxx")
        }, 
        {
            "_id" : ObjectId("yyy")
        }
    ]
}

users is an array, which can contain two or more than two objects.
If I've to request strictly two objects via a mongo query, how can I do it?

.find({ 
    "users._id" : { $in: [ObjectId("xxx"), ObjectId("yyy")] }
})

This above query will fetch all the docs that've either've xxx user or yyy user in them. How can I form a query where if the both xxx and yyy are only there, then only that doc is to be fetched.
Let me know if you need more info to understand the problem. And huge thanks in advance for the help.

Upvotes: 1

Views: 624

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22316

You should use $all to force the need for all ids in the array to match but it is not enough on it's own as you'll still match documents with those two users + other users.

To combat that you will also have to make sure the users array is of size 2, you can do it like so:

db.collection.find({
  $and: [
    {
      "users._id": {
        $all: [
          ObjectId("609a80e3c548140e5859d6de"),
          ObjectId("60136b272c1e946545da6204")
        ]
      }
    },
    {
      "users.2": {
        $exists: false
      }
    }
  ]
})

Mongo Playground

Upvotes: 1

Related Questions