gpt4 book ai didi

mongodb - 在 mongoDB 中通过属性构建进行分组

转载 作者:行者123 更新时间:2023-12-04 10:13:32 25 4
gpt4 key购买 nike

我有一个名为 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 中通过属性构建进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61203003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com