2011-09-14 120 views
26

比方說,我有以下文件mongoDB不同&在相同的查詢?

Article { Comment: embedMany } 

Comment { Reply: embedMany } 

Reply { email: string, ip: string } 

我要作出這樣的選擇不同Reply.ip其中Reply.email = xxx

這樣的事情,只是它不工作查詢..

db.Article.find("Comment.Reply.email" : "xxx").distinct("Comment.Reply.ip") 

JSON輸出:

{ 
    "_id":{ 
     "$oid":"4e71be36c6eed629c61cea2c" 
    }, 
    "name":"test", 
    "Comment":[ 
     { 
     "name":"comment test", 
     "Reply":[ 
      { 
       "ip":"192.168.2.1", 
       "email":"yyy" 
      }, 
      { 
       "ip":"127.0.0.1", 
       "email":"zzz" 
      } 
     ] 
     }, 
     { 
     "name":"comment 2 test", 
     "Reply":[ 
      { 
       "ip":"128.168.1.1", 
       "email":"xxx" 
      }, 
      { 
       "ip":"192.168.1.1", 
       "email":"xxx" 
      } 
     ] 
     } 
    ] 
} 

我跑db.Article.distinct("Comment.Reply.ip",{"Comment.Reply.email" : "xxx"})

我希望["128.168.1.1", "192.168.1.1"]

我得到:符合條件蒙戈["127.0.0.1", "128.168.1.1", "192.168.1.1", "192.168.2.1"]

+3

有我給予好評的「我跑」,「我期待「,」我得到「,如果只有格式化的所有問題都是這樣! – adelriosantiago

+1

這是一個解決方案的變種 http://stackoverflow.com/a/13864518/358013 – blueskin

回答

36

Distinct查詢是這樣的

db.Article.distinct("Comment.Reply.ip",{"Comment.Reply.email" : "xxx"}) 

沒有其他方式

編輯:

我現在明白了這個問題,序匹配/過濾器的子文檔,我們需要使用$ elemMatch運營商,像這樣

db.Article.distinct("Comment.Reply.ip",{Comment: {$elemMatch: {"Reply.email" : "xxx"}}}) 

但如果子文檔包含子數組,則這不起作用(在你的情況下,你有一系列的回覆)。現有問題$elemMatch on subArray已打開。其計劃爲mongo 2.1。您可以檢查出的鏈接獲取更多信息

+0

我試過了,它似乎忽略條件,所以結果是一樣的db.Article.distinct(「Comment.Reply.ip 「) – Inoryy

+0

@Inori,上面的代碼在我的環境中工作得非常好......你可以發佈你的實際數據和你得到的結果,所以我可以挖掘... – RameshVel

+0

請檢查更新的第一篇文章 – Inoryy

0

也許你可以試試這個

db.Article.aggregate([ 
{$unwind: "$Comment"}, 
{$unwind: "$Comment.Reply"}, 
{$match: {"Comment.Reply.email": "xxx"}}, 
{$group: {_id: "$Comment.Reply.ip"}} 
]) 

例子的結果應該是

/* 1 */ 
{ 
    "_id" : "192.168.1.1" 
} 

/* 2 */ 
{ 
    "_id" : "128.168.1.1" 
}