在聚合期间从同一文档中的属性创建键值对
During aggregation creating key value pairs from properties in the same document
我有一个具有多个属性的文档。例如
{
name: "Some name",
business: "object-id",
price: 10,
category: "Some category",
}
在聚合过程中,我尝试为 属性 业务匹配对象 ID,然后我尝试按类别将它们分组到 return 数组。该数组将包含每个类别的一个对象,以及一个包含使用名称 -> 价格的键值对的对象的数组。这是我目前拥有的:
collection.aggregate([
{ $match: { business: ObjectId(req.params.businessId) } },
{
$group: {
_id: "$category",
}
}
]).toArray()
我找不到如何使用包含名称 -> 价格键值对的对象生成数组。例如:
[
{_id: "a category", services: [{name:"service1", price:10}, {name:"service2", price:15}]},
{_id: "second category", services: [{name:"service1", price:10}, {name:"service2", price:10}]}
{_id: "third category", services: [{name:"service1", price:5}, {name:"service2", price:55}]}
]
提前感谢您的帮助。
使用mongodb的$push
特性即可实现需求。
collection.aggregate([
{ $match: { business: ObjectId(req.params.businessId) } },
{
$group: {
_id: "$category",
services: { $push: { name: "$name", price: "$price" } }
}
}
]).toArray()
我有一个具有多个属性的文档。例如
{
name: "Some name",
business: "object-id",
price: 10,
category: "Some category",
}
在聚合过程中,我尝试为 属性 业务匹配对象 ID,然后我尝试按类别将它们分组到 return 数组。该数组将包含每个类别的一个对象,以及一个包含使用名称 -> 价格的键值对的对象的数组。这是我目前拥有的:
collection.aggregate([
{ $match: { business: ObjectId(req.params.businessId) } },
{
$group: {
_id: "$category",
}
}
]).toArray()
我找不到如何使用包含名称 -> 价格键值对的对象生成数组。例如:
[
{_id: "a category", services: [{name:"service1", price:10}, {name:"service2", price:15}]},
{_id: "second category", services: [{name:"service1", price:10}, {name:"service2", price:10}]}
{_id: "third category", services: [{name:"service1", price:5}, {name:"service2", price:55}]}
]
提前感谢您的帮助。
使用mongodb的$push
特性即可实现需求。
collection.aggregate([
{ $match: { business: ObjectId(req.params.businessId) } },
{
$group: {
_id: "$category",
services: { $push: { name: "$name", price: "$price" } }
}
}
]).toArray()