Tree
Tree

Reputation: 31411

query array particular array elements in mongodb

I have collection of

{array:[1,2,3]},
{array:[1,2,4]},
{array:[2,1,2]} 

How to return all objects where array has

[1,2,*anyNumber]

to get result

{array:[1,2,3]},
{array:[1,2,4]},

Upvotes: 0

Views: 47

Answers (1)

Mandeep Singh
Mandeep Singh

Reputation: 8234

If you want the ordering to be exactly the same, i.e. first element to be 1 and second element to be 2, then use

db.coll.find({"array.0": 1, "array.1": 2})

However, this will also return docs where there is no element at index 3. If you want the third element to be present, use this:

db.coll.find({"array.0": 1, "array.1": 2, "array.2": {"$exists": true}})

Also, this will return arrays whose length can be greater than 3. If you are specifically looking for arrays whose length is 3 only, then you may use $where to check the length

db.coll.find({"array.0": 1, "array.1": 2, "array.2": {"$exists": true}, $where:'this.array.length==3'})

If this is complicated and you are just looking for documents where array contains 1 and 2 irrespective of the ordering and irrespective of presence of a third element, then simply use:

db.coll.find({"array": {"$all": [1,2]}})

Upvotes: 1

Related Questions