我在MongoDB中使用聚合,现在我遇到了一个问题,我想根据条件匹配与否来投影我的字段。
例如,我有一个字段coupon_type
,我将检查其值是否等于 1,然后我将投影字段["curr_ctr", "total_coupons"]
否则,如果其值不等于 1,那么我将投影字段["curr_ctr", "total_coupons", "curr_ctr", "coupons"].
可以使用两个查询并并行运行它们,但我正在尝试使用一个查询来实现我的结果。
任何人都可以告诉我如何在一个查询中做到这一点?
更新
我的文件如下
[{ "_id" : ObjectId("5878e1edf1df5a2b69bcf60e"), "curr_ctr": 12, "total_coupons":35, "coupons": ["hello", "hello2"], "coupon_type" : 1 } ,
{ "_id" : ObjectId("5878e1eff1df5a2b69bcf60f"), "curr_ctr": 12, "total_coupons":35, "coupons": ["hello", "hello2"], "coupon_type" : 0 } ,
{ "_id" : ObjectId("5878e1f1f1df5a2b69bcf610"), "curr_ctr": 12, "total_coupons":35, "coupons": ["hello", "hello2"], "coupon_type" : 1 } ,
{ "_id" : ObjectId("5878e1f3f1df5a2b69bcf611"), "curr_ctr": 12, "total_coupons":35, "coupons": ["hello", "hello2"], "coupon_type" : 1 } ,
{ "_id" : ObjectId("5878e1f5f1df5a2b69bcf612"), "curr_ctr": 12, "total_coupons":35, "coupons": ["hello", "hello2"], "coupon_type" : 11 } ,
{ "_id" : ObjectId("5878e1f7f1df5a2b69bcf613"), "curr_ctr": 12, "total_coupons":35, "coupons": ["hello", "hello2"], "coupon_type" : 110 },
{ "_id" : ObjectId("5878e1f9f1df5a2b69bcf614"), "curr_ctr": 12, "total_coupons":35, "coupons": ["hello", "hello2"], "coupon_type" : 0 } ]
现在,对于所有等于 0 coupon_type,我想投影字段["curr_ctr", "total_coupons", "curr_ctr", "coupons"]
,对于所有不等于 0 coupon_type,我想投影字段["curr_ctr", "total_coupons"]
更新
实际上我想coupons
数组从索引 n 投影到 n+1,其中 n 是用户的输入。
让我们考虑您的集合包含以下文档
[{ "_id" : ObjectId("5878e1edf1df5a2b69bcf60e"), "coupon_type" : 1 } ,
{ "_id" : ObjectId("5878e1eff1df5a2b69bcf60f"), "coupon_type" : 0 } ,
{ "_id" : ObjectId("5878e1f1f1df5a2b69bcf610"), "coupon_type" : 1 } ,
{ "_id" : ObjectId("5878e1f3f1df5a2b69bcf611"), "coupon_type" : 1 } ,
{ "_id" : ObjectId("5878e1f5f1df5a2b69bcf612"), "coupon_type" : 11 } ,
{ "_id" : ObjectId("5878e1f7f1df5a2b69bcf613"), "coupon_type" : 110 },
{ "_id" : ObjectId("5878e1f9f1df5a2b69bcf614"), "coupon_type" : 0 } ]
现在您需要在project
中使用$eq
作为:
db.collectoin.aggregate({
"$project": {
"result": {
"$cond": {
"if": {
"$eq": ["$coupon_type", 1]
},
"then": ["curr_ctr", "total_coupons"],
"else": ["curr_ctr", "total_coupons", "curr_ctr", "coupons"]
}
}
}
})
根据新的更新,您应该像这样修改查询:
db.collection.aggregate({
"$project": {
"result": {
"$cond": {
"if": {
"$eq": ["$coupon_type", 1]
},
"then": ["$curr_ctr", "$total_coupons", "$coupons"],
"else": ["$curr_ctr", "$total_coupons"]
}
}
}
})
更新
根据新的更新,让我们考虑用户给出的n
,例如:var n = 1
;
现在查询将如下所示:
db.coupon.aggregate({
"$project": {
"result": {
"$cond": {
"if": {
"$eq": ["$coupon_type", 1]
},
"then": ["$curr_ctr", "$total_coupons", {
"coupons": {
"$slice": ["$coupons", n, n + 1]
}
}],
"else": ["$curr_ctr", "$total_coupons"]
}
}
}
})