mongoDB 不同,在同一个查询中在哪里?

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

最佳答案

Distinct 在 mongo 中使用条件的查询是这样的

 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。您可以查看链接了解更多信息

关于mongoDB 不同,在同一个查询中在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7419986/

相关文章:

java - 如何在其字段之一中检索具有最大值的文档 Mongodb

mongodb - 我应该如何在 MongoDB 中存储属于多个其他对象的对象?

javascript - Mongoose - 检测重复字段

MongoDb 数据库与集合

node.js - Mongodb 搜索功能未执行

mongodb - 元组(数组)作为 mongoose.js 中的属性

django.core.exceptions.ImproperlyConfigured : name must be an instance of basestring

mongodb全文搜索多个短语

node.js - 在 OpenShift 上扩展 MongoDB 与使用 MongoLab

node.js - 如何从mongodb中的对象数组中获取特定的数组元素