rhymn
rhymn

Reputation: 141

How do I query nested objects within an array to match an $in array in mongodb?

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.

Upvotes: 0

Views: 29

Answers (2)

Ezra Siton
Ezra Siton

Reputation: 7741

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

Upvotes: 1

rhymn
rhymn

Reputation: 141

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

I found this query to solve my problem.

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

Upvotes: 0

Related Questions