【问题标题】:Aggregation $cond if condition implementation in JavaJava 中的聚合 $cond if 条件实现
【发布时间】:2017-06-15 04:59:18
【问题描述】:

我想在java中实现'if condition'我不知道怎么做,所以给点建议

db.test.aggregate(
       [
          {
             $project:
               {
                 data: 1,
                 result:
                   {
                     $cond: { if: { $cond: [ "$salary", 250000 ] }, then: 30, else: 20 }
                   }
               }
          }
       ]
    )

【问题讨论】:

    标签: java mongodb aggregation-framework


    【解决方案1】:

    只需 DocumentsLists

    List<Document> pipeline = Arrays.asList(
      new Document("$project",
        new Document("data1", 1)
          .append("result", new Document(
            "$cond", new Document(
              "if", new Document("$eq", Arrays.asList("$salary", 250000) )
            )
            .append("then", 30)
            .append("else", 20) 
          ))
      )
    );
    

    序列化为:

    [
      { "$project": {
        "data1": 1,
        "result": {
          "$cond": {
            "if": { "$eq": [ "$salary", 250000 ] },
            "then": 30,
            "else": 20
          }
        }
      }}
    ]
    

    或者交替使用$cond的“列表”形式:

    List<Document> pipeline = Arrays.asList(
      new Document("$project",
        new Document("data1", 1)
          .append("result", new Document(
            "$cond", Arrays.asList(
              new Document("$eq", Arrays.asList("$salary", 250000) ),
              30,
              20
            )
          ))
      )
    );
    

    序列化为:

    [
      { "$project": {
        "data1": 1,
        "result": {
          "$cond": [
            { "$eq": [ "$salary", 250000 ] },
            30,
            20
          }
        }
      }}
    ]
    

    两者都是$cond 的有效用法。

    还要注意您的问题中的错误,您可能是指 $eq 或者您可能是指 $gt 或条件上的其他逻辑运算符。 $cond 期望“如果”返回一个布尔值。

    根据驱动程序,您可以将 Document 替换为 BasicDBObject

    【讨论】:

      猜你喜欢
      • 2016-11-01
      • 2019-02-25
      • 2018-08-03
      • 1970-01-01
      • 2017-05-23
      • 2020-06-21
      • 2012-08-06
      • 1970-01-01
      相关资源
      最近更新 更多