2017-01-06 40 views
2

我有一個函數,它應該返回在給定的時間段內創建的用戶數,並且按邀請和未邀請的組來創建組。在$cond運營商,我需要比較,如果字段tkbSponsor不是null並不等於[email protected]。如果這個條件結果爲真,那麼該用戶被邀請。否則,他沒有被邀請。

var countByPeriod = function(req,res) { 
    var initialDate = req.body.initialDate; 
    var finalDate = req.body.finalDate; 

    User.aggregate([ 
     { 
      "$match": { 
       "timeStamp": { 
        "$gte": new Date(initialDate), 
        "$lt": new Date(finalDate) 
       } 
      } 
     }, 
     { 
      "$group": { 
       "_id": null, 
       "total": { "$sum": 1 }, 
       "invited": { 
        "$sum": { 
         "$cond": [ 
          { 
           "tkbSponsor": { 
            "$nin": ["[email protected]",null] 
           } 
          }, 
          1, 
          0 
         ] 
        } 
       } 
      } 
     } 
    ], (err,result) => { 
     if (!err) { 
      if (result.length) res.send(result[0]); 
      else res.send({"total": 0,"invited":0}); 
     } else { 
      res.sendStatus(500); 
      console.log(err); 
     } 

    }); 

}; 

順便說一句,在執行時該功能是給我的錯誤:

{ [MongoError: invalid operator '$nin'] 
    name: 'MongoError', 
    message: 'invalid operator \'$nin\'', 
    ok: 0, 
    errmsg: 'invalid operator \'$nin\'', 
    code: 15999 } 

只是一個觀察。我以前用的是$cond操作如下,因爲我沒有必要跟null比較:

"$cond": [ 
      { 
      "$ne": ["$tkbSponsor", "[email protected]"] 
      }, 
      1, 
      0 
] 

和它的作品。但是,現在我還要比較tkbSponsor是否爲空並且使用$nin,是否給我這個錯誤。

回答

0

改變,要與$ifNull聚結作爲$and一起使用:

{ 
    "$cond": [ 
     { 
      "$and": [ 
       { "$ne": ["$tkbSponsor", "[email protected]"] }, 
       { 
        "$ne": [ 
         { "$ifNull": [ "$tkbSponsor", null ] }, 
         null 
        ] 
       } 
      ] 
     }, 1, 0 
    ] 
} 

,或者使用$or作爲

{ 
    "$cond": [ 
     { 
      "$or": [ 
       { "$eq": ["$tkbSponsor", "[email protected]"] }, 
       { 
        "$eq": [ 
         { "$ifNull": [ "$tkbSponsor", null ] }, 
         null 
        ] 
       } 
      ] 
     }, 0, 1 
    ] 
} 

$ifNull操作者的存在是作爲一個$exists運營商通過用null值替換「不存在」或空字段進行評估。

運行,應返回正確的結果作爲較早revision只評估文件,其中tkbSponsorexists和具有以下任一null值或「[email protected]」。

隨着$ifNull,「不存在」字段也評估爲運營商給他們空值。

+0

與''''null'''equals用'''存在'''運算符進行比較?該查詢正在運行,但結果不正確。我猜想與'''null'''的比較總是正確的。 – Chittolina

+0

你可以編輯你的問題給一些樣本文件進行測試,並顯示你期望來自該樣本的正確結果嗎? – chridam