【问题标题】:Nested conditions in $cond aggregate$cond 聚合中的嵌套条件
【发布时间】:2016-11-01 17:38:19
【问题描述】:

我正在尝试在我的 Mongo 查询中创建一个计算的 status 字段(状态:已创建、已收到付款、已发货、已收到、已完成)。

db.orders.aggregate( [
   { $project: { status: {
      $cond: { if: { $ne: ["$feedback", null] }, 
      then: 'finished', else: {
         $cond: { if: { $ne: ["$received", null] }, 
         then: 'received', else: {
            $cond: { if: { $ne: ["$shipped", null] }, 
            then: 'shipped', else: {
               $cond: { if: { $ne: ["$payment", null] }, 
                  then: 'payment received', else: 'created' }
            } }
         } } 
      } }
   } } },
   { $match: {  } }
] )

示例数据:

{
    "_id" : "xxxxxx0",
    "payment" : ISODate("2016-02-03T10:45:00.011Z"),
    "shipped" : ISODate("2016-02-03T11:55:00.011Z"),
    "received" : ISODate("2016-02-03T12:45:00.011Z"),
    "feedback" : ISODate("2016-02-03T14:34:00.011Z")
},
{
    "_id" : "xxxxxx1",
    "payment" : ISODate("2016-02-03T10:45:00.011Z"),
    "shipped" : ISODate("2016-02-03T11:55:00.011Z"),
    "received" : ISODate("2016-02-03T12:45:00.011Z")
},
{
    "_id" : "xxxxxx2",
    "payment" : ISODate("2016-02-03T10:45:00.011Z"),
    "shipped" : ISODate("2016-02-03T11:55:00.011Z")
},
{
    "_id" : "xxxxxx3",
    "payment" : ISODate("2016-02-03T10:45:00.011Z")
},
{
    "_id" : "xxxxxx4"
}

由于某种原因,我的所有结果都显示为“已完成”,我是否使用 $cond 错误?是否支持嵌套 $cond ?

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    如果要检查字段是否存在,则不能使用 $eq null ,它将始终返回 true 使用 $gt 有一个技巧可以做到这一点。你可以在这里查看完整的解释(https://docs.mongodb.com/manual/reference/bson-types/#bson-types-comparison-order

    db.orders.aggregate( [
       { $project: { status: {
          $cond: { if: { $gt: ["$feedback", null] }, 
          then: 'finished', else: {
             $cond: { if: { $gt: ["$received", null] }, 
             then: 'received', else: {
                $cond: { if: { $gt: ["$shipped", null] }, 
                then: 'shipped', else: {
                   $cond: { if: { $gt: ["$payment", null] }, 
                      then: 'payment received', else: 'created' }
                } }
             } } 
          } }
       } } },
       { $match: {  } }
    ] )
    

    【讨论】:

    • 您先生,真是个天才!保存了我的查询! :)
    猜你喜欢
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多