根据不同的条件设计不同的领域

时间:2017-01-13 13:35:53

标签: mongodb mongodb-query aggregation-framework

我在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是用户的输入。

1 个答案:

答案 0 :(得分:1)

考虑您的收藏包含以下文件

[{ "_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 } ]

现在您需要在$eq中使用project作为:

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"]
      }
    }
  }
})