如何只显示相同 属性 个车把的一个数据?
how to show only one data for the same property Handlebars?
所以我有这个数据:
{
item: "paint",
unit: "4",
price: "15",
date : ISODate("2020-06-22T07:30:09")
}
{
item: "paint",
unit: "1",
price: "5",
date : ISODate("2020-06-22T07:30:15")
}
{
item: "glue",
unit: "2",
price: "9",
date : ISODate("2020-06-22T07:30:16")
}
我的模板是这样的:
{{#costs}}
<p>{{item}} = {{unit}}</p>
{{/costs}}
结果会是这样的:
paint = 4
paint = 1
glue = 2
我的问题是,如何只显示一个具有相同 属性 名称(项目)的数据?
所以我可以实现这样的目标:
paint = 5
glue = 2
您需要聚合管道来对项目进行分组并进行 $sum。在求和之前也将其转换为整数。
db.test.aggregate([{ $group: { _id: "$item", totalUnits: { $sum: {$toInt: "$unit"} } } }])
以上查询将为您提供结果:
{ "_id" : "paint", "totalUnits" : 5 }
{ "_id" : "glue", "totalUnits" : 2 }
所以我有这个数据:
{
item: "paint",
unit: "4",
price: "15",
date : ISODate("2020-06-22T07:30:09")
}
{
item: "paint",
unit: "1",
price: "5",
date : ISODate("2020-06-22T07:30:15")
}
{
item: "glue",
unit: "2",
price: "9",
date : ISODate("2020-06-22T07:30:16")
}
我的模板是这样的:
{{#costs}}
<p>{{item}} = {{unit}}</p>
{{/costs}}
结果会是这样的:
paint = 4
paint = 1
glue = 2
我的问题是,如何只显示一个具有相同 属性 名称(项目)的数据? 所以我可以实现这样的目标:
paint = 5
glue = 2
您需要聚合管道来对项目进行分组并进行 $sum。在求和之前也将其转换为整数。
db.test.aggregate([{ $group: { _id: "$item", totalUnits: { $sum: {$toInt: "$unit"} } } }])
以上查询将为您提供结果:
{ "_id" : "paint", "totalUnits" : 5 }
{ "_id" : "glue", "totalUnits" : 2 }