gpt4 book ai didi

node.js - 使用 $min 选择字段的最小值并在 mongodb 中聚合

转载 作者:太空宇宙 更新时间:2023-11-03 23:28:11 25 4
gpt4 key购买 nike

我想获取包含所有字段的文档,以将 $min 与我的集合中的特定字段进行聚合。

下面是我的集合结构,

{
"_id" : ObjectId("585e7454b0a2683a0f6a3617"),
"postid":100,
"region" : "IN",
"brand" : "Uber",
"used" : 4
}

{
"_id" : ObjectId("585e7454b0a2683a0f6a35b7"),
"postid":101,
"region" : "UK",
"brand" : "Airbnb",
"used" : 7
}

{
"_id" : ObjectId("585e7454b0a2683a0f6a3619"),
"postid":102,
"region" : "US",
"brand" : "Uber",
"used" : 9
}
{
"_id" : ObjectId("585e7454b0a2683a0f6a3619"),
"postid":103,
"region" : "US",
"brand" : "Airbnb",
"used" : 2
}
{
"_id" : ObjectId("585e7454b0a2683a0f6a3619"),
"postid":104,
"region" : "US",
"brand" : "Home",
"used" : 17
}

我想通过“已使用”字段的 $min 值获取文档品牌的独特值。

我想得到这样的输出,

{
"_id" : ObjectId("585e7454b0a2683a0f6a3617"),
"postid":100,
"region" : "IN",
"brand" : "Uber",
"used" : 4
}

{
"_id" : ObjectId("585e7454b0a2683a0f6a3619"),
"postid":103,
"region" : "US",
"brand" : "Airbnb",
"used" : 2
}
{
"_id" : ObjectId("585e7454b0a2683a0f6a3619"),
"postid":104,
"region" : "US",
"brand" : "Home",
"used" : 17
}

目前我正在使用此查询,

db.sales.aggregate(
[
{
$group:
{
_id: "$brand",
used: { $min: "$used" }
}
}
]
);

提前致谢

最佳答案

如果您想在组中包含其他字段,最好使用 $first $last 累加器,但在订购您的文档之后。在这种情况下,您需要使用 $sort 运算符作为您的第一个管道步骤,然后按升序对文档进行分组:

db.sales.aggregate([
{ "$sort": { "brand": 1, "used": 1 } },
{
"$group": {
"_id": "$brand",
"postid": { "$first": "$postid" },
"region": { "$first": "$region" },
"docId": { "$first": "$_id" },
"used": { "$first": "$used" }
}
}
])

关于node.js - 使用 $min 选择字段的最小值并在 mongodb 中聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41382045/

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