如何在 MongoDB 聚合中按字符串而不是 ObjectId 分组?
How can I group by a string instead of ObjectId in MongoDB aggregate?
我有两个集合,它们之间是多对一的关系:
产品:
"_id" : ObjectId("61cc81c9585946c3b44f24411"),
"name" : "some random name",
"price" : 100,
"description" : "description",
"category_id" : ObjectId("61cc8100585946c3b44f2317d")
类别:
{
"_id" : ObjectId("61cc8100585946c3b44f2317d"),
"description" : "Category description",
"name" : "Electronics"
}
我想输出每个类别的最高产品价格:
db.product.aggregate([
{ "$group": {
"_id": "$category_id",
"max": { "$max": "$price"}
}}
])
这很好用,因为它向我打印了以下内容:
{ "_id" : ObjectId("61cc80fb585946c3b44f697c"), "max" : 62}
{ "_id" : ObjectId("61cc8100585946c3b44f697d"), "max" : 100}
但是有没有办法从类别中获取“名称”而不是其对象 ID?
我知道在 SQL 中你会按 category_name 分组,但它在这里似乎不起作用。
根据@prasad 的建议,您应该在 $group
阶段之后使用 $lookup
阶段。
db.product.aggregate([
{
"$group": {
"_id": "$category_id",
"max": {
"$max": "$price"
}
}
},
{
"$lookup": {
"from": "category",
"localField": "_id",
"foreignField": "_id",
"as": "categoryName",
}
},
{
"$set": {
"categoryName": {
"$arrayElemAt": [
"$categoryName.name",
0
]
}
}
}
])
我有两个集合,它们之间是多对一的关系:
产品:
"_id" : ObjectId("61cc81c9585946c3b44f24411"),
"name" : "some random name",
"price" : 100,
"description" : "description",
"category_id" : ObjectId("61cc8100585946c3b44f2317d")
类别:
{
"_id" : ObjectId("61cc8100585946c3b44f2317d"),
"description" : "Category description",
"name" : "Electronics"
}
我想输出每个类别的最高产品价格:
db.product.aggregate([
{ "$group": {
"_id": "$category_id",
"max": { "$max": "$price"}
}}
])
这很好用,因为它向我打印了以下内容:
{ "_id" : ObjectId("61cc80fb585946c3b44f697c"), "max" : 62}
{ "_id" : ObjectId("61cc8100585946c3b44f697d"), "max" : 100}
但是有没有办法从类别中获取“名称”而不是其对象 ID?
我知道在 SQL 中你会按 category_name 分组,但它在这里似乎不起作用。
根据@prasad 的建议,您应该在 $group
阶段之后使用 $lookup
阶段。
db.product.aggregate([
{
"$group": {
"_id": "$category_id",
"max": {
"$max": "$price"
}
}
},
{
"$lookup": {
"from": "category",
"localField": "_id",
"foreignField": "_id",
"as": "categoryName",
}
},
{
"$set": {
"categoryName": {
"$arrayElemAt": [
"$categoryName.name",
0
]
}
}
}
])