【问题标题】:mongoDB distinct & where in same query?mongoDB 不同,在同一个查询中在哪里?
【发布时间】:2011-09-14 16:49:08
【问题描述】:

假设我有以下文件

Article { Comment: embedMany }

Comment { Reply: embedMany }

Reply { email: string, ip: string }

我想做一个查询,选择不同的Reply.ip where 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"]

【问题讨论】:

  • 请为“我跑步”、“我期望”、“我得到”投上一票,只要所有问题的格式都像这样!
  • 这是解决方案的变体stackoverflow.com/a/13864518/358013

标签: mongodb


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

【讨论】:

  • 我试过了,好像忽略条件,所以结果和db​​.Article.distinct("Comment.Reply.ip")
  • @Inori,上面的代码在我的环境中工作得很好......你能发布你的实际数据和你得到的结果,以便我可以挖掘......
  • 猜猜我必须等待 2.1 :/ 无论如何感谢您的回复!
【解决方案2】:

也许你可以试试这个

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

【讨论】:

    【解决方案3】:

    db.collection.distinct("field_name", query)

    将以数组的形式从您的集合中返回所有不同的值

    field_name 应该是您要为其返回不同值的字段。

    query 指定要从中检索不同值的文档。例如:- {"Comment.Reply.email" : "xxx"}{'country' : 'India','state' : 'MH','city' : 'mumbai'}

    【讨论】:

    • 这个真的不错。我试图为此编写聚合查询。
    【解决方案4】:
    distinctdates=db.dailyreport_detailed.find(
    
    {'uid':personemail,'month':searchdate2,'year':searchdate1}
    )
    
    .distinct('date_only')
    

    其中 find 将根据条件检索,最后的 distinct 将给出唯一日期。

    【讨论】:

    • 这不起作用。它返回:'distinct 不是函数'
    猜你喜欢
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    相关资源
    最近更新 更多