4

I am trying to find in a collection all of the documents that have the given key equal to one of the strings in an array.

Heres an example of the collection.

{
  roomId = 'room1',
  name = 'first'
},
{
  roomId = 'room2',
  name = 'second'
},
{
  roomId = 'room3',
  name = 'third'
}

And heres an example of the array to look through.

[ 'room2', 'room3' ]

What i thought would work is...

collection.find({ roomId : { $in : [ 'room2', 'room3' ]}}, function( e, r )
{
  // r should return the second and third room
});

How can i achieve this?

One way this could be solve would be to do a for loop...

var roomIds = [ 'room2', 'room3' ];
for ( var i=0; i < roomIds.length; i++ )
{
  collection.find({ id : roomIds[ i ]})
}

But this is not ideal....

2
  • Are these standalone documents or are they embedded into some "hotel" document? What do you actually get as a result? Commented Jun 7, 2012 at 13:44
  • The 3 documents you see are root documents in a collection. Commented Jun 7, 2012 at 13:45

1 Answer 1

7

What you posted should work - no looping required. The $in operator does the job:

> db.Room.insert({ "_id" : 1, name: 'first'});
> db.Room.insert({ "_id" : 2, name: 'second'});
> db.Room.insert({ "_id" : 3, name: 'third'});
> // test w/ int
> db.Room.find({ "_id" : { $in : [1, 2] }});
{ "_id" : 1, "name" : "first" }
{ "_id" : 2, "name" : "second" }
> // test w/ strings
> db.Room.find({ "name" : { $in : ['first', 'third'] }});
{ "_id" : 1, "name" : "first" }
{ "_id" : 3, "name" : "third" }

Isn't that what you expect?

Tested w/ MongoDB 2.1.1

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

2 Comments

Ahh your correct, it is working... It appears the query is working but the update i had in mind is not. I want that each room in the array is found, (which currently is working) and that they are all updated with { $addToSet : { members : member.id }}. But the update is not working. It appears only the first item found is being updated. How can i change this?
Ahh found it, i use { multi : true }. Thanks for getting me in the right direction.

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.