2015-10-14 84 views
2

我有一個文件的集合,其中一個字段的名稱是不同的,但它意味着同樣的事情。 所以我希望能夠做類似SQL CASE語句的東西:MongoDB查詢選擇一個字段,如果其他爲空

SELECT CASE 
     WHEN field1 IS NULL THEN field2 
     ELSE field1 

最重要的是,我需要做一個彙總:

db.coll.aggregate(
    [ 
    { 
     $group: 
     { 
      _id: "fieldID", 
      maxThing: { $max: { $divide: [ "fieldA", "fieldB" ] } } 
      ELSE IF fieldA IS NULL 
      maxThing: { $max: { $divide: [ "fieldC", "fieldD" ] } } 
     } 
    } 
    ] 
) 

想法?

謝謝!

+0

您的解釋不明確,請嘗試重構您的查詢並添加一些關於您的文檔模式設計的代碼。 – sergiuz

回答

2

最好使用$ifNull運營商在聚集管道:

對於第一種情況,你可以在$project流水線階段使用它:

db.coll.aggregate([ 
    { 
     $project: { 
      "item": 1, 
      "field1": { "$ifNull": [ "$field1", "$field2" ] } 
     } 
    } 
]) 

至於其他的情況:

db.coll.aggregate([ 
    { 
     $group: { 
      "_id": "$fieldID", 
      "maxThing": { 
       "$max": { 
        "$divide": [ 
         { "$ifNull": [ "$fieldA", "$fieldC" ] } , 
         { "$ifNull": [ "$fieldB", "$fieldD" ] } 
        ] 
       } 
      }  
     } 
    } 
]) 
+0

{$ project:{field ... ifnull ....}}有效。聚合也適用。但是,總計只有*一半*的作品。它只提供結果,如果提供的一個字段爲空。 – Bear

+0

看起來像[**原始問題**](http://stackoverflow.com/questions/33136093/mongodb-query-select-one-field-if-the-other-is-null)解決不是它?至於上述評論,這將是Stack Exchange站點上的一個** [不同的問題](http://meta.stackexchange.com/questions/43478/exit-strategies-for-chameleon-questions),「變色龍問題」不太受歡迎「)**,請考慮單獨發佈。 – chridam

0

我收回它。它確實工作,使用它在這個簡單的測試案例,下面。但在我的生產環境中,它失敗了。有些地方一定是不對的。我需要弄清楚。

JSON: 
{ 
    "id" : "Identifier A", 
    "fieldA" : 1, 
    "fieldB" : 2 
}, 
{ 
    "id" : "Identifier B", 
    "fieldC" : 3, 
    "fieldD" : 4 
} 

QUERY: 
db.test.aggregate(
    [{ 
     $group: { 
      _id: "$id", 

      maxOfDiv: { 
       $max: { 
        $divide: [{ 
         "$ifNull": ["$fieldA", "$fieldC"] 
        }, { 
         "$ifNull": ["$fieldB", "$fieldD"] 
        }] 
       } 
      } 
     } 
    }] 
) 
相關問題