mongodb - 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"}]
}
]
解决方案
$group
通过userId
并构造docs
具有必填字段的数组$group
docs
通过 null 并以键值格式构造数组$arrayToObject
将docs
数组转换为对象$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" } } }
])
推荐阅读
- python-3.x - 当我在另一个函数中调用一个函数时,返回值不会被打印出来,所以我需要使用 print 函数
- class - Dart:如何访问另一个类中对象的类属性?(嵌套类)
- r - oob=scales::squish 不适用于 ggplot2 中的 scale_size_continuous
- reactjs - 如何隐藏 URL 扩展名以防止访问页面
- ios - 如何使用委托和协议传递数据
- django - 表“avc.consumptions_message”不存在
- unit-testing - 如何将 POST 请求 multipart/form-data 字段作为数组发送以进行单元测试?
- arrays - 通过 Swift 编程访问二维数组中的值
- java - 如何使用 Java 将图像编码为 AVIF?
- python - 离线安装python模块