【发布时间】:2017-01-15 20:31:06
【问题描述】:
我在 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 } ]
现在对于所有的 coupon_type 等于 0 我要投射字段 ["curr_ctr", "total_coupons", "curr_ctr", "coupons"] 并且对于所有 coupon_type 不等于 0 我要投射字段 ["curr_ctr", "total_coupons"]
更新
其实我想将coupons数组从索引n投影到n+1,其中n是用户的输入。
【问题讨论】:
-
是的,您可以使用 $cond 执行此操作
-
我知道 $cond 但是如何使用 $cond 来投影不同的字段?你能告诉我这样做的代码吗??
-
发布示例文档和预期输出以及您尝试了什么的更好方法?
-
正如我已经提到的,我的字段都与上面相同,关于我尝试过的内容,我看到了这个 $cond 但不知道如何在我的场景中使用它。
标签: mongodb mongodb-query aggregation-framework