【问题标题】:Mongo Aggregate Group List / Filtered ResultsMongo 聚合组列表/过滤结果
【发布时间】:2021-04-16 22:39:06
【问题描述】:

这里是我的 mongdb 记录

{ "_id" : 1,"userId" : "x",  "name" : "Central", "borough": "Manhattan"},
  { "_id" : 2,"userId" : "x", "name" : "Rock", "borough" : "Queens"},
  { "_id" : 3,"userId" : "y", "name" : "Empire", "borough" : "Brooklyn"},
  { "_id" : 4,"userId" : "y", "name" : "Stana", "borough" : "Manhattan"},
  { "_id" : 5,"userId" : "y", "name" : "Jane", "borough" :"Brooklyn"}

我们如何通过 userId 这样的字段获取结果

[
  { 
    x : [{"_id":1,"name":"Central"},{"_id":2,"name":"Rock"}],
    y:[{ "_id" : 3,"name":"Empire"},{ "_id" : 4,"name":"Stana"},{ "_id" : 5,"name":"Jane"}]
  }
]

【问题讨论】:

  • 您的响应结果不是有效的json格式,您能纠正一下吗?
  • 这是样本先生,没关系更正,如果可能的话,我需要按分组字段的对象或数组结果
  • 我知道我所说的语法是无效的,我无法预测你想要的结果是它的 2 个文档数组还是单个文档,你对这两个文档的要求是什么 1) [ { x: [], y: [] } ] 2) [ { x: [] }, { y: [] } ]
  • 感谢您的建议路径,我根据您建议的路径 2 修改了您的帖子

标签: mongodb aggregation-framework


【解决方案1】:
  • $group by userId 并使用必填字段构造 docs 数组
  • $group by null 并以键值格式构造docs数组
  • $arrayToObjectdocs 数组转换为对象
  • $replaceRoot 将上面转换的对象替换为根
db.collection.aggregate([
  {
    $group: {
      _id: "$userId",
      docs: {
        $push: {
          _id: "$_id",
          name: "$name"
        }
      }
    }
  },
  {
    $group: {
      _id: null,
      docs: {
        $push: {
          k: "$_id",
          v: "$docs"
        }
      }
    }
  },
  { $replaceRoot: { newRoot: { $arrayToObject: "$docs" } } }
])

Playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 2015-10-06
    • 2020-09-05
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    相关资源
    最近更新 更多