2012-06-07 29 views
3

我想在集合中找到所有具有與數組中的某個字符串相同的鍵的文檔。MongoDB找到哪裏的鍵等於從數組中的字符串

繼承人一個集合的例子。

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

而繼承人是數組要查看的示例。

[ 'room2', 'room3' ] 

什麼,我想會的工作是...

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

我怎樣才能做到這一點?這可以解決

一個辦法是爲循環做...

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

但這並不理想....

+0

這些獨立文檔還是嵌入某些「酒店」文檔?你究竟得到什麼結果? –

+0

您看到的3個文檔是集合中的根文檔。 – cnotethegr8

回答

7

你貼什麼應該工作 - 無需循環。該$in運營商做工作:

> 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" } 

這不正是你期待什麼?

經測試w/MongoDB 2.1.1

+0

啊,你的正確,它正在工作......看起來查詢正在工作,但我想到的更新不是。我希望找到數組中的每個房間(當前正在工作),並且它們全都使用'{$ addToSet:{members:member.id}}'更新。但更新不起作用。看來只有找到的第一個項目正在更新。我怎樣才能改變這一點? – cnotethegr8

+1

Ahh發現它,我使用'{multi:true}'。感謝您讓我走向正確的方向。 – cnotethegr8

相關問題