我有一个名为 Accounts 的集合,如下数据
/* 1 */
{
"_id" : ObjectId("5e93fea52f804ab99b54e4a2"),
"account" : "first",
"connect" : "Always",
"desc" : "first account feature first phase",
"status" : true
}
/* 2 */
{
"_id" : ObjectId("5e93fea32c804ab99b12e4d1"),
"account" : "second",
"connect" : "Sometimes",
"desc" : "second account feature first phase",
"status" : true
}
/* 3 */
{
"_id" : ObjectId("5e93fea52f804ab99b55a7b1"),
"account" : "first",
"connect" : "Sometimes",
"desc" : "first account feature second phase",
"status" : true
}
尝试以查询应返回如下结构的结果的方式对数据进行分组和构造
/* First Row */
"account" : "first",
[
{
_id:ObjectId("5e93fea52f804ab99b54e4a2")
"connect" : "Always",
"desc" : "first account feature first phase",
"status" : true
},
{
_id:ObjectId("5e93fea52f804ab99b55a7b1")
"connect" : "Sometimes",
"desc" : "first account feature second phase",
"status" : true
},
]
/* Second Row */
"account" : "second",
[
{
_id:ObjectId("5e93fea32c804ab99b12e4d1")
"connect" : "Always",
"desc" : "second account feature first phase",
"status" : true
},
]
希望与帐户进行分组,并且相应的帐户行应该包含该 ID 的其他相关数据。
我尝试过的
我尝试编写以下查询
db.accounts.aggregate(
{
$match : {account : {$in: ["first", "second"]}}
}
,
{
$group : {
_id : "$account"
}
}
);
但这部分工作正常,返回帐户列表,例如第一个、第二个但不相关的属性。
谢谢
最佳答案
在$group
之后使用$push
累加器获取分组数据数组
db.accounts.aggregate([
{
$match: { account: { $in: ["first", "second"] } },
},
{
$group: {
_id: "$account",
data: { $push: "$$ROOT" },
},
}
]);
关于mongodb - mongoDB 中的 Group by 与属性构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61203003/