2017-01-13 38 views
1

我在下面運行一個聚合函數。文檔可能有也可能沒有元素,我只想返回true/false。如果元素確實存在,元素是巨大的,所以返回整個元素會產生很多問題並且不需要。

爲了解決這個問題,我在3.0.4版本的生產環境中升級到3.4版本,但目前這不是一個選項,雖然看起來版本有更好的解決方案。

爲了測試這個,我有一個集合mycollection的文檔。該文檔有一個元素exists,它是包含其他元素的對象。它不會有一個元素稱爲notexists

db.runCommand({ 
    "aggregate": "mycollection", 
    "pipeline": [{ 
     "$match": {...} 
    }, { 
     "$sort": {...} 
    }, { 
     "$group": {...} 
    }, { 
     "$limit": 10 
    }, { 
     "$project": { 
      "aggregated": { 
       "$map": { 
        "input": "$mycollection", 
        "as": "document", 
        "in": { 
         "exists_test":{"$eq":["$$document.exists",null]}, 
         "not_exists_test":{"$eq":["$$document.notexists",null]}, 
         "exists_test_ifnull":{"$ifNull":["$$document.exists","test"]}, 
         "not_exists_test_ifnull":{"$ifNull":["$$document.notexists","test"]}, 
         "exists_content": "$$document.exists" 
         ... 
        } 
       } 
      }, 
      "success": { 
       "$cond": { 
        "if": { "$gt": ["$status", 0] }, 
        "then": "false", 
        "else": "true" 
       } 
      } 
     } 
    }] 
}) 

不幸的是,這將返回一個文件:

{ 
    aggregated: [{ 
     "exists_test": false, (correct) 
     "not_exists_test": false, (wrong) 
     "exists_test_ifnull": content from document.exists, (correct) 
     "not_exists_test_ifnull": "test", (correct) 
     "exists_content": content from document.exists, (correct) 
    }] 
} 

看來"not_exists_test":{"$eq":["$$document.notexists",null]},應返回true,因爲$ifNull沒有準確地反映該值爲空。

+1

嘗試''not_exists_test「:{」$ gt「:[」$$ document.notexists「,null]},如[BSON types comparison order](http://docs.mongodb.org/手動/參考/ BSON類型/#BSON類型對比順序)。 – chridam

+0

!!輝煌!這是完美的。謝謝!添加它作爲答案,我會標記它是正確的。 – DAB

回答

相關問題