1

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.

2
  • 1
    try $all operator instead of $in. Commented May 27, 2021 at 9:00
  • yes. $all is working fine. thanks! Commented May 27, 2021 at 10:01

1 Answer 1

1

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

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

2 Comments

Awesome. It's working even if we have more than two users. But can you please tell me what this "user.2" is doing. I understand that it is checking for length of 2, but can you point me out to mongo docs, so I can read more about it.
'users.2' is the 2 index in an array, so if users.2 exists than it means the array has at least 3 items in it.

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.