[英]How can I filter array of objects into MongoDB Document
I'm using Express as my backend and MongoDB as the data base.我使用 Express 作为后端,使用 MongoDB 作为数据库。 My models looks like this:我的模型如下所示:
Pyments:皮门:
var pymentSchema = new mongoose.Schema({
name: {
type: String,
enum: [
"VISA",
"MASTERCARD",
"CASH",
],
required: [true, "Need a type of pyment"],
},
total: {
type: Number,
default:0
},
});
Bill:账单:
var billingSchema = new mongoose.Schema({
pyments: {
type: [Pyments],
required: true,
default:[]
}});
My stored data looks like this:我存储的数据如下所示:
"Bill": [
{
"_id": "5fe17af4a0f04d088ca24d36",
"pyments": [
{
"total": 1.6,
"name": "VISA"
},
{
"total": 1.25,
"name": "CASH"
}
]
},
{
"_id": "5fe8d6ede7adc919d4299d02",
"pyments": [
{
"total": 1.61,
"name": "VISA"
},
{
"total": 1.00,
"name": "MASTERCARD"
},
]
},
{
"_id": "5fea68a2eb0e382a50dae7a6",
"pyments": [
{
"total": 2.5,
"name": "VISA"
},
{
"total": 3.38,
"name": "MASTERCARD"
}
]
}]
All I want is to get for example the total only in VISA
, CASH
and MASTERCARD
like this: (Object returned)我想要的只是获得例如仅在VISA
、 CASH
和MASTERCARD
中的总数,如下所示:(返回对象)
{
"Totals": [
{
"total": 5.71,
"name": "VISA"
},
{
"total": 1.25,
"name": "CASH"
},
{
"total": 4.38,
"name": "MASTERCARD"
}
]
}
I really don't have an idea what to do in this case, any help will be appreciated.我真的不知道在这种情况下该怎么做,任何帮助将不胜感激。
You can use aggregation method aggregate() , and below pipeline stages,您可以使用聚合方法aggregate() ,并在管道阶段以下,
$unwind
deconstruct pyments
array $unwind
解构pyments
数组$group
by pyments.name
and get total sum of pyment.total
using $sum
$group
by pyments.name
并使用$sum
获取pyment.total
的总和BillSchemaModel.aggregate([
{ $unwind: "$pyments" },
{
$group: {
_id: "$pyments.name",
total: { $sum: "$pyments.total" }
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.