0

Data structure

{
    users: [
        {id: "aaa"},
        {id: "bbb"},
        {id: "ccc"}
    ]
},
{
    users: [
        {id: "111"},
        {id: "222"},
        {id: "333"}
    ]
},


array: ["111", "222", "333"]

I want to get the document where every "id" matches my array, like $in does. But I don't want matches where only two of three matches. So in this case, the query should return the second document.

2 Answers 2

1

One way:

Query an array for an element

const cursor = db.collection('inventory').find({
  users: [{id: "111"},{id: "222"},{id: "333"}]
});

https://docs.mongodb.com/manual/tutorial/query-arrays/#query-an-array-for-an-element

Related Q: MongoDB Find Exact Array Match but order doesn't matter

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

Comments

0
const userIds = ["abc", "123", ...]

I found this query to solve my problem.

    {
    $and: [
        {users: {$elemMatch: {id: {$in: userIds}}}}, 
        {users: {$size: userIds.length}}
    ]
}

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.