mongoDB独特&在同一查询中的哪里? [英] mongoDB distinct & where in same query?

查看:54
本文介绍了mongoDB独特&在同一查询中的哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下文件

Article { Comment: embedMany }

Comment { Reply: embedMany }

Reply { email: string, ip: string }

我要查询一个选择不同的Reply.ip的地方,其中Reply.email = xxx

I want to make a query that selects distinct Reply.ip where Reply.email = xxx

像这样的东西,只有它是行不通的.

Something like this, only it doesn't work..

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

推荐答案

Distinct在mongo中具有条件的查询是这样的

Distinct query in mongo with condition works like this

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

别无选择

我现在了解问题了,为了匹配/过滤子文档,我们需要使用$ elemMatch运算符,例如

I understand the problem now, inorder to match/filter subdocuments we need to use $elemMatch operator, like this

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

,但是如果子文档包含子数组(在您的情况下,您具有答复数组),则此方法将不起作用.存在 $ elemMatch on subArray 上存在的问题.并计划在mongo 2.1中使用.您可以查看链接以获取更多信息

but this will not work if the sub-document contains sub arrays (in your case, you have array of replies). There is an existing issue $elemMatch on subArray is opened. And its planned for mongo 2.1. You can check out the link for more info

这篇关于mongoDB独特&在同一查询中的哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆