3

If I have a field in a mongodb document which has an array, for example:

"tags" : [  "tag", "etc1",  "etc2",  "etc3" ]

Is there a way that I can select that document if it contains the element 'etc1'?
If I try using the query:

db.coll.find({"tags" : { $elemMatch: { value0: 'etc1'} }})

but I need to know the position of the element in the array, which I don't know.
I have also tried:

db.coll.find({"tags" : { $elemMatch: 'etc1' }})

but it needs to be an object. Is there any way of doing this?

NB I am using mongoose but I wasn't sure how to construct the query

user2521439
  • 1,405
  • 2
  • 13
  • 19
  • Please do not post with statements such as "but if it needs to be an object". Please actually show your **real** data and what you actually are trying to do. Change the names to protect the innocent, but show your actual needs. – Neil Lunn Apr 07 '14 at 11:39

2 Answers2

6

Use the $in operator as described in this question or this other question and as described in the mongodb docs and can be accessed in mongoose.

With it, you'll have a query that looks something like this...remembering that you must pass an array when using $in:

db.coll.find({"tags" : { $in : ['etc1'] } } );

Community
  • 1
  • 1
Matthew Bakaitis
  • 11,600
  • 7
  • 43
  • 53
3

Apart from using $in operator you can also use $all operator like:

db.col1.find({"tags":{$all :["etc1"]}})
Saheed Hussain
  • 1,096
  • 11
  • 12