MongoDB 分组
MongoDB GroupBy
我有mongoDBcollection这样
{
"_id" : "EkKTRrpH4FY9AuRLj",
"stage" : 10,
},
{
"_id" : "EkKTRrpH4FY9AuRLj",
"stage" : 10,
},
{
"_id" : "EkKTRrpH4FY9AuRLj",
"stage" : 20,
}
我想把它分组在
stage: 10 in paid
stage: 20 in unpaid
结果应该是这样的
{
"paid": [
{
"_id" : "EkKTRrpH4FY9AuRLj",
"stage" : 10,
},
{
"_id" : "EkKTRrpH4FY9AuRLj",
"stage" : 10,
}
],
"unpaid": [
{
"_id" : "EkKTRrpH4FY9AuRLj",
"stage" : 20,
}
]
}
我该怎么做?
建议使用 aggregation framework for this where you'd need to run an initial $group
staged pipeline that uses the operators $push
to create the new arrays, and $cond
评估某些条件并使用逻辑嵌入正确的文档。
最终的 $project
pipeline step is necessary to prune some of the array elements from the previous pipeline that are redundant, i.e. filter out the [false] values by using the $setDifference
运算符。
考虑 运行 以下显示 mongo shell 中的聚合管道:
db.collection.aggregate([
{
"$group": {
"_id": null,
"paid": {
"$push": {
"$cond": [
{ "$eq": [ "$stage", 10 ] },
{ "_id": "$_id", "stage": "$stage" },
false
]
}
},
"unpaid": {
"$push": {
"$cond": [
{ "$eq": [ "$stage", 20 ] },
{ "_id": "$_id", "stage": "$stage" },
false
]
}
}
}
},
{
"$project": {
"_id": 0,
"paid": {
"$setDifference": [ "$paid", [false] ]
},
"unpaid": {
"$setDifference": [ "$unpaid", [false] ]
}
}
}
])
在 Mongo.Collection 个实例上添加 meteorhacks:aggregate
package that exposes .aggregate()
方法。请注意,这仅适用于服务器端,并且没有内置的观察支持或反应性。
使用
添加到您的应用
meteor add meteorhacks:aggregate
我有mongoDBcollection这样
{
"_id" : "EkKTRrpH4FY9AuRLj",
"stage" : 10,
},
{
"_id" : "EkKTRrpH4FY9AuRLj",
"stage" : 10,
},
{
"_id" : "EkKTRrpH4FY9AuRLj",
"stage" : 20,
}
我想把它分组在
stage: 10 in paid
stage: 20 in unpaid
结果应该是这样的
{
"paid": [
{
"_id" : "EkKTRrpH4FY9AuRLj",
"stage" : 10,
},
{
"_id" : "EkKTRrpH4FY9AuRLj",
"stage" : 10,
}
],
"unpaid": [
{
"_id" : "EkKTRrpH4FY9AuRLj",
"stage" : 20,
}
]
}
我该怎么做?
建议使用 aggregation framework for this where you'd need to run an initial $group
staged pipeline that uses the operators $push
to create the new arrays, and $cond
评估某些条件并使用逻辑嵌入正确的文档。
最终的 $project
pipeline step is necessary to prune some of the array elements from the previous pipeline that are redundant, i.e. filter out the [false] values by using the $setDifference
运算符。
考虑 运行 以下显示 mongo shell 中的聚合管道:
db.collection.aggregate([
{
"$group": {
"_id": null,
"paid": {
"$push": {
"$cond": [
{ "$eq": [ "$stage", 10 ] },
{ "_id": "$_id", "stage": "$stage" },
false
]
}
},
"unpaid": {
"$push": {
"$cond": [
{ "$eq": [ "$stage", 20 ] },
{ "_id": "$_id", "stage": "$stage" },
false
]
}
}
}
},
{
"$project": {
"_id": 0,
"paid": {
"$setDifference": [ "$paid", [false] ]
},
"unpaid": {
"$setDifference": [ "$unpaid", [false] ]
}
}
}
])
在 Mongo.Collection 个实例上添加 meteorhacks:aggregate
package that exposes .aggregate()
方法。请注意,这仅适用于服务器端,并且没有内置的观察支持或反应性。
使用
添加到您的应用meteor add meteorhacks:aggregate