更新时间:2023-08-25 23:13:58
您基本上使用 $cond
在这里:
You basically use $setIsSubset
and $cond
here:
var userId= "5add82620d7f5b38240c63d4";
Model.aggregate([
{ "$group": {
"_id": null,
"numberOfUnreadOffers": {
"$sum": {
"$cond": {
"if": {
"$setIsSubset": [[mongoose.Types.ObjectId(userId)], "$readBy"]
},
"then": 0,
"else": 1
}
}
}
}}
])
当然,您还需要使用mongoose.Types.ObjectId
从字符串"投射"到有效的ObjectId
值.
Of course you also need to "cast" using mongoose.Types.ObjectId
from the "string" to a valid ObjectId
value.
但是,实际上,您可以通过简单的 count()
来获得更好的性能:
But really you get better performance from a simple count()
instead:
Model.count({ "readBy": { "$ne": userId } })
因此,您实际上根本不应该使用.aggregate()
.
So you really should not use .aggregate()
for this at all.