2011-09-14 72 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" 
}