听起来你想把事情组合在一起。有一个叫做
aggregation framework
在mongodb中。
你可以用它做很多事情,其中之一就是分组。
更多信息,请阅读
$group
例如:
-
在“2017-11-26T16:00:00Z”中,我们有6个苹果,价格为15
-
在“2017-11-25T16:00:00Z”中,我们有4个苹果,价格为16
-
在“2017-10-25T16:00:00Z”中,我们有9个苹果,价格为30
1.
假设我们有三个条目:
/* 1 */
{
"_id" : ObjectId("5a1adc774d8a2fe38bec83e4"),
"date" : ISODate("2017-11-26T16:00:00.000Z"),
"apples" : 6,
"price" : 15
}
/* 2 */
{
"_id" : ObjectId("5a1adc924d8a2fe38bec83e8"),
"date" : ISODate("2017-11-25T16:00:00.000Z"),
"apples" : 4,
"price" : 16
}
/* 3 */
{
"date" : ISODate("2017-10-25T16:00:00.000Z"),
"apples" : 9,
"price" : 30
}
现在,我们想按月对它们进行分组,并对每个月的苹果数求和,我们可以做到以下几点:
db.yourCollection.aggregate([
{
$project:
{
month: { $month: "$date" },
apples: 1, // here we just assign the value of apples. There is no change here
price: 1 // also just assigning the value to price. Nothing is happening here.
}
},
{
$group: // grouping phase
{
_id: "$month", // This is what we group by
monthApples: {$sum: "$apples"} // here we sum the apples per month
monthPrice: {$sum: "$price"} // here we sum the price for each month
}
}
])
在
$project
我们可以利用
date aggregation operators
.
上述聚合管道将导致:
/* 1 */
{
"_id" : 10, // month (October)
"monthApples" : 9 // sum of apples
"monthPrice" : 30 // sum of price for month 10
}
/* 2 */
{
"_id" : 11, // month (November)
"monthApples" : 10 // sum of apples
"monthPrice" : 31 // sum of price for month 11
}
2.
现在想象一下,我们有苹果类型也保存在数据库中。
/* 1 */
{
"_id" : ObjectId("5a1adc774d8a2fe38bec83e4"),
"date" : ISODate("2017-11-26T16:00:00.000Z"),
"apples" : 6,
"price" : 15,
"appleType" : "Goldrush"
}
/* 2 */
{
"_id" : ObjectId("5a1adc924d8a2fe38bec83e8"),
"date" : ISODate("2017-11-25T16:00:00.000Z"),
"apples" : 4,
"price" : 16,
"appleType" : "Pink Lady"
}
/* 3 */
{
"_id" : ObjectId("5a1b1c144d8a2fe38bec8a56"),
"date" : ISODate("2017-10-25T16:00:00.000Z"),
"apples" : 9,
"price" : 30,
"appleType" : "Pink Lady"
}
例如,我们可以这样按苹果类型分组。
db.yourCollection.aggregate([
{
$project:
{
apples: 1, // here we just assign the value of apples. There is no change here
price: 1, // also just assigning the value to price. Nothing is happening here.
appleType: 1
}
},
{
$group: // grouping phase
{
_id: "$appleType", // group by appletype
monthApples: {$sum: "$apples"}, // here we sum the apples per month
monthPrice: {$sum: "$price"} // here we sum the price for each month
}
}
])