James Yang
James Yang

Reputation: 1416

Find document that matches same array elements in MongoDB

Think of these documents in MongoDB:

{id:1, people:['james', 'john', 'candy']}
{id:2, people:['james', 'john', 'candy', 'gary']}

How can I find document that match only full set of array elements, regardless of the order of array elements.

For example if I input this:

input=[ 'candy', 'james', 'john' ]

The matching response should be document id:1.

If I had any other documents with exact same 3 people, regardless of their order in MongoDB people array, it should also match.

I've tried $all, but this did not work.

Upvotes: 2

Views: 530

Answers (2)

Rubin Porwal
Rubin Porwal

Reputation: 3845

As a solution to your problem please try executing following query in mongodb.

db.getCollection('collection').find({"people":{$all:[ 'james', 'john', 'candy' ]}})

The above query will perform exact match of array elements regardless of their order

Upvotes: -1

Ayano
Ayano

Reputation: 541

You can use $size to limit the array's size:

db.test.find({
   "people": { $all: [ 'james', 'john', 'candy' ], $size: 3 }
})

Upvotes: 2

Related Questions