首页 > 解决方案 > Mongo 聚合组列表/过滤结果

问题描述

这里是我的 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"}]
  }
]

标签: mongodbaggregation-framework

解决方案


  • $group通过userId并构造docs具有必填字段的数组
  • $groupdocs通过 null 并以键值格式构造数组
  • $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" } } }
])

操场


推荐阅读