2016-06-29 4 views
0

私のMongoクエリ(ステータス:作成、支払い受領、出荷、受信、終了)で計算ステータスフィールドを作成しようとしています。

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: { } } 
]) 

例のデータ:すべての私の結果は、私が$ condが間違って使用しています、 '終了' と表示何らかの理由で

{ 
    "_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をサポートしていますか?

答えて

4

フィールドが存在するかどうかをチェックする場合は、$ 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: { } } 
]) 
+0

あなたは天才です!私の質問を保存しました! :) – Asaf