14

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?

2
  • 1
    Is $in really what you're looking for? docs Commented Apr 22, 2013 at 10:51
  • 1
    An example of your current query and the result you are trying to achieve would be very helpful. It sounds like you do want an $in query. Commented Apr 22, 2013 at 13:04

2 Answers 2

14

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

Sign up to request clarification or add additional context in comments.

2 Comments

$in takes only arrays: "Can't canonicalize query: BadValue $in needs an array"
@RaxWunter -- correct. Not sure why I had that as I did confirm it behaves that way as of 2.6. Thanks! (This was from April 2013 so something may changed in the console or DB ... not sure what happend :) )
5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.