MongoDB – $ nin无效的运算符与聚合
我有一个function,应该返回一个给定的时间内创build的用户数和组邀请和未邀请。 在$cond
操作符上,我需要比较字段tkbSponsor
是否为null
,而不是等于example@example.com
。 如果这个条件结果为真,那么该用户被邀请。 否则,他没有被邀请。
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": ["example@example.com",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", "example@example.com"] }, 1, 0 ]
它工作。 但是,现在我也要比较,如果tkbSponsor
不为空,并使用$nin
,给我这个错误。
将其更改为使用$and
并与$ifNull
coalesce一起使用:
{ "$cond": [ { "$and": [ { "$ne": ["$tkbSponsor", "example@example.com"] }, { "$ne": [ { "$ifNull": [ "$tkbSponsor", null ] }, null ] } ] }, 1, 0 ] }
或使用$or
as
{ "$cond": [ { "$or": [ { "$eq": ["$tkbSponsor", "example@example.com"] }, { "$eq": [ { "$ifNull": [ "$tkbSponsor", null ] }, null ] } ] }, 0, 1 ] }
$ifNull
操作符的存在是充当$exists
操作符,用null
值replace“不存在”或空字段以进行评估。
运行此应该返回正确的结果,因为早期版本只是评估tkbSponsor
字段exists
文档,并且值为null
或“example@example.com”。
使用$ifNull
,也会评估“不存在”字段,因为运算符$ifNull
它们设为空值。