Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a $elemMatch on first level array?

Consider the following document:

{
  "_id" : "ID_01",
  "code" : ["001", "002", "003"],
  "Others" : "544554"
}

I went through this MongoDB doc for elemmatch-query & elemmatch-projection, but not able to figure it out how to use the same for the above document.

Could anyone tell me how can I use $elemMatch for the field code?

like image 647
Amol M Kulkarni Avatar asked Apr 22 '13 07:04

Amol M Kulkarni


2 Answers

If you're simply looking to match all documents with an array containing a given value, you can just specify the value on the reference to that array, e.g.

db.mycodes.find( { code: '001' } )

Which thus would return you all documents that contained '001' in their code array

like image 137
Joshua Avatar answered Oct 19 '22 04:10

Joshua


You'll want to use the $in operator rather than $elemMatch in this case as $in can be used to search for a value (or values) inside a specific field. $in requires a list of values to be passed as an array. Additionally, and for your case, it will find either a single value, or by searching in an array of values. The entire matching document is returned.

For example, you might use it like this:

db.mycodes.find( { code: { $in: ["001"] } } )

Which could be simplified to just be:

db.mycodes.find({ code: "001" })

As MongoDB will look in an array for a single match like above ("001").

Or if you want to search for "001" or "002":

db.mycodes.find( { code: { $in: ["001", "002"] } } )

$in documentation

like image 40
WiredPrairie Avatar answered Oct 19 '22 05:10

WiredPrairie