I need to retrieve documents that contain at least one value inside an array. The structure of my document is:
{ "_id": 3,
"username": "111111",
"name": "XPTO 1",
"codes": [ 2, 4, 5 ],
"available": true }
{ "_id": 4,
"username": "22222",
"name": "XPTO 2",
"codes": [ 3, 5 ],
"available": true }
I need to do a find by “codes” and if i search for value “5”, i need to retrieve all documents that contains this value inside their array.
I’ve tried to use #elemMatch but no success…
db.user.find({codes: {"$elemMatch": {codes: [2,8]}}}, {"codes":1})
How can i do this?
Thanks in advance.
You can check for values inside an array just like you compare the values for some field.
So, you would need to do it like this, without using $elemMatch: –
If you want to check whether an array contain a single value 5: –
This will return all the document, where
codesarray contain5.If you want to check whether an array contain a value out of given set of values: –
This will return documents with array containing either 2 or 8
If you want to check whether an array contain all the values in a list: –
This will return all document with array containing both 2 and 5.