2013-05-02 73 views
1

如何查詢與數組中對象的確切字段匹配的集合?如何查詢與數組中對象的確切字段匹配的集合

由於測試用例更加明確,因此這裏是要通過的測試。

a = Invitation.create(guests: [ Guest.new(player: 'bbb'), Guest.new(player: 'ccc') ]) 
b = Invitation.create(guests: [ Guest.new(player: 'ccc'), Guest.new(player: 'bbb') ]) 
c = Invitation.create(guests: [ Guest.new(player: 'bbb'), Guest.new(player: 'ccc'), Guest.new(player: 'ddd') ]) 

# Request to find invitation with bbb and ccc as player_id of guests, regardless the order. 
result = Invitation.collection.find(...) 
assert_equal result, [ a, b ] 

我用例是一個邀請系統,其中的客人相同的組合可以不存在,所以當發送一個新的邀請,我需要檢查,如果一個完全相同的人(不管它們的順序)。

注:我使用一個Guest對象數組,因爲它攜帶一些額外的數據。這裏是一個示例數據集(https://gist.github.com/anonymous/5507735)。

+0

你能提供一個mongo記錄的例子嗎? db.Invitation.findOne()會做的。 – shargors 2013-05-02 19:05:47

+0

我編輯帖子以添加示例數據集(https://gist.github.com/anonymous/5507735)。 – 2013-05-03 07:35:58

回答

1

根據nyde1319的回答;這種感覺稍微的hackish,但因爲這裏有沒有其他解答得好:

db.invitation.find({'guests.player':{'$all':['bbb','ccc']}, guests: {$size: 2}}) 

在課程{$size: 2}數2取決於數組的長度。

+0

它運作良好。謝謝! – 2013-05-03 18:00:05

1

也許$all是你所需要的。我不知道你正在使用的ORM還是什麼模式,但是這裏有一個樣本蒙戈外殼輸出:

> db.invitation.find({'guests.player':{'$all':['bbb','ccc']}}) 
{ "_id" : ObjectId("518319079468428b381d3563"), "guests" : [ { "player" : "bbb" }, { "player" : "ccc" } ] } 
{ "_id" : ObjectId("518319239468428b381d3566"), "guests" : [ { "player" : "ccc" }, { "player" : "bbb" } ] } 
{ "_id" : ObjectId("518319b39468428b381d3567"), "guests" : [ { "player" : "ccc" }, { "player" : "bbb" }, { "player" : "ddd" } ] } 

如果你只想要那些含有'bbb'只有'ccc',你可以嘗試以下方法:

db.inv.find({'guests.player':{$all:['bbb','ccc']}, 
    'guests':{$not:{$elemMatch:{'player':{$nin:['bbb','ccc']}}}}}) 

這給:

[ 
    { "_id" : ObjectId("518319079468428b381d3563"), 
     "guests" : [ { "player" : "bbb" }, { "player" : "ccc" } ] }, 
    { "_id" : ObjectId("518319239468428b381d3566"), 
     "guests" : [ { "player" : "ccc" }, { "player" : "bbb" } ] } 
] 

如果你想'bbb''ccc',只需更換$all$in。這在某種程度上是異或實現,但我不確定它是否覆蓋了您的所有用例。

+0

問題是我不想要第三個記錄。我只想邀請BBB和CCC球員(不管順序如何)。我不想要那些含有BBB,CCC和DDD的。 – 2013-05-03 07:26:24

+0

請參閱我的編輯。 – MervS 2013-05-03 11:03:26

+0

謝謝。我相信Juho的回答是更好的選擇。 – 2013-05-03 18:02:13

相關問題