【问题标题】:MongoDB aggregate and group for different key names不同键名的 MongoDB 聚合和分组
【发布时间】:2017-04-18 21:57:54
【问题描述】:

这是我在这里的第一篇文章,真的希望得到帮助。

我去找MongoDB aggregate result with two different keys 但无法获得相同的相关性。或者更确切地说,我可能无法遵守解决方案

问题是我有一个集合,其中文档具有不同的键。基于该键,结果数据将作为对象数组获得。 下面是集合结构

{
"_id" : ObjectId("58ec840e2573065a1e076db3"),
"uniqueid" : "24050951",
"productid" : "5149-1550DM-11",
"record_id" : 1
}

{
"_id" : ObjectId("58ec840e2573065a1e076db4"),
"task" : 1,
"record_id" : 1,
"judgement" : {
    "2" : "Functional"
}
}


{
"_id" : ObjectId("58ec840e2573065a1e076db5"),
"qc" : 1,
"record_id" : 1,
"judgement" : {
    "2" : "No Style"
}
}

{
"_id" : ObjectId("58ec840e2573065a1e076db6"),
"task" : 2,
"record_id" : 1,
"judgement" : {
    "2" : "Functional"
}
}

{
"_id" : ObjectId("58ec840e2573065a1e076db6"),
"task" : 2,
"record_id" : 2,
"judgement" : {
    "2" : "Functional"
}
}

我期望的输出是三个数组的对象

"task"-> Array(3)-> contains three records for record_id 1 and 2 and also one more for task 1 and 2 for record_id 1
"qc" -> Array(1)
"other" -> if the task or qc doesnot exist.

很容易将其作为 mongo 函数获取,您可以在其中编写 javascript 代码。但就我而言,使用聚合有点复杂。 任何帮助将不胜感激

谢谢

【问题讨论】:

  • 这不是聚合那么...
  • 你的mongodb服务器版本是多少?
  • @Veeram 使用 3.4
  • 问题的状态是什么?如果它不起作用,则给出了答案但未接受或在其下放置评论。如果解决了,请考虑接受答案以将问题标记为已解决@Neo
  • @Fred-ii- 抱歉延迟回复。被抓住了。无论如何它并没有解决问题

标签: mongodb


【解决方案1】:

您可以尝试使用$facet$match 检查字段是否存在 ($exist)。

db.collection.aggregate( [
  {
    $facet: {
      "task": [
           { $match: { task: { $exists: 1 } } }
      ],
      "qc": [
           { $match: { qc: { $exists: 1 } } },
      ],
      "other": [
          { $match: {task: { $exists: 0 } , qc: { $exists: 0 } } },
      ]
    }
  }
]) 

【讨论】:

    【解决方案2】:

    给你!

    db.data.aggregate([
        {$group:{_id:null, task:{$push:"$task"}, qc:{$push:"$qc"}, other:{$pushAll:['$record_id','$judgement']} }}
    ])
    

    注意:为了获取除 task 和 qc 之外的所有字段,请按照指示将这些键放入另一个 $pushAll 数组中

    【讨论】:

    • @nurulnabi ...对不起兄弟它没有按预期工作。感谢您的回复
    • 你能告诉我,上述查询的输出是什么,应该是什么?我的意思是我不知道问题出在哪里。我可以纠正吗?
    猜你喜欢
    • 2014-05-10
    • 2019-04-01
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 2021-04-19
    • 2017-07-21
    • 1970-01-01
    相关资源
    最近更新 更多