MongoDB时获取组"/>
使用MongoDB时获取组
我需要在mongoDB中使用group
计算一些记录,但就我而言,_id
数组即将到来。我在下面解释我的查询。
let query = {
$group: {
_id: "$Products.ProductName",
dispatchcount: { $sum: 1 },
totalDispatchValue: {$sum:"$TotalAmount.TotalPayment"},
totalDiscountValue: {$sum: "$TotalDiscount.TotalDiscountAmount"}
}
}
pipeLine.push(query);
const orders = await dispatchOrdersCol.aggregate(pipeLine);
此查询正在生成以下输出
[
{
"_id": [
"Unisex Navy Blue Belt"
],
"dispatchcount": 1,
"totalDispatchValue": 27922,
"totalDiscountValue": 4084
},
{
"_id": [
"Writing Ruled Note Book",
"Physics Record Book",
"Chemistry Record Book",
"Computer Science Record Book"
],
"dispatchcount": 1,
"totalDispatchValue": 2190,
"totalDiscountValue": 0
},
{
"_id": [
"PU2-Physics Part-1 Text Book",
"PU2-Physics Part-2 Text Book",
"PU2-Mathematics Part - 1 Text Book",
"PU2-Chemistry Part - 1 Text Book",
"PU2-English Text Book",
"PU2-Mathematics Part - 2 Text Book",
"PU2-Chemistry Part - 2 Text Book",
"PU2-English Work Book",
"PU2-TEXT BOOK",
"PU2-Sanskrit Text Book",
"Boys White & Blue Striped Half Shirt",
"Boys Navy Blue Regular Fit Trousers",
"Illume Calf-length Cotton Black Socks "
],
"dispatchcount": 1,
"totalDispatchValue": 4131,
"totalDiscountValue": 150
},
{
"_id": [
"PU2-TEXT BOOK"
],
"dispatchcount": 1,
"totalDispatchValue": 1679,
"totalDiscountValue": 0
}
]
此处为_id
键,这里有多个值,下一个记录中还会重复一些值。我在下面解释猫鼬模型。
const Model = new Schema({
DispatchId: { type: Number, required: true },
OrderNumber: { type: String, unique: true, required: true },
OrderStatus: { type: String },
OrderType: { type: String },
DispatchPriority: { type: String },
Comments: { type: Array },
Products: { type: Array },
Customer: { type: Object },
TotalDiscount: { type: Object },
TotalShipping: { type: Object },
TotalCoupon: { type: Object },
TotalAmount: { type: Object },
PaymentDetails: { type: Object },
ClientDetails: { type: Object },
DispatchCreatedAt: { type: String },
DispatchUpdatedAt: { type: String },
IsActive: { type: Boolean }
},
{
timestamps: {
createdAt: 'CreatedAt',
updatedAt: 'UpdatedAt'
},
collection: DISPATCH_ORDERS_COLLECTION
}
);
这里我需要根据产品名称计算total Payment and total Discount
。但是在我的情况下,一个产品也要在两个记录中出现两次。
在您的文档中Products
是一个数组,(带有字段ProductName
的对象的数组),当您执行"$Products.ProductName"
时,它将为您提供产品名称的数组。因此,您需要在$unwind
阶段之前对Products数组执行$group
:
不正确的查询:
db.collection.aggregate([
/** You don't need this addFields stage, just given to test, you can remove `$group` stage & check the `products` field value */
{
$addFields: {
products: "$products.productName"
}
},
{
$group: {
_id: "$products"
}
}
])
测试: mongoplayground
正确的查询:
db.collection.aggregate([
{
$unwind: "$products"
},
{
$addFields: {
products: "$products.productName"
}
},
{
$group: {
_id: "$products"
}
}
])
测试: mongoplayground
Ref: $unwind
更多推荐
使用MongoDB时获取组
发布评论