计算值与数组不匹配的地方 [英] Count where value does not match array
问题描述
我有以下offers
集合
此处readBy
包含用户的_id
...
现在,我要计算userId = "5add82620d7f5b38240c63d4"
Here readBy
contains the _id
of the users...
Now I want to count the number of unRead offers for the userId = "5add82620d7f5b38240c63d4"
{
"_id" : ObjectId("5aeaab5ed6a9c97d0209260a"),
"expiresIn" : ISODate("2018-05-30T18:30:00.000Z"),
"name" : "Trip ",
"readBy" : [
ObjectId("5add82620d7f5b38240c63d4"),
ObjectId("5add82620d7f5b38240c63c6")
],
"__v" : 0
}
{
"_id" : ObjectId("5aeaab7dd6a9c97d0209260b"),
"expiresIn" : ISODate("2018-05-29T18:30:00.000Z"),
"name" : "Trip",
"readBy" : [ObjectId("5add82620d7f5b38240c63d4")],
"__v" : 0
}
{
"_id" : ObjectId("5aeae233d6a9c97d02092622"),
"expiresIn" : ISODate("2018-05-25T18:30:00.000Z"),
"name" : "two way off",
"readBy" : [],
}
{
"_id" : ObjectId("5aeae49643f10d284726069c"),
"expiresIn" : ISODate("2018-05-25T18:30:00.000Z"),
"name" : "two way off",
"readBy" : [],
}
{
"_id" : ObjectId("5aeae49743f10d284726069d"),
"expiresIn" : ISODate("2018-05-25T18:30:00.000Z"),
"name" : "two way off",
"readBy" : []
}
{
"_id" : ObjectId("5aeae49743f10d284726069e"),
"expiresIn" : ISODate("2018-05-25T18:30:00.000Z"),
"name" : "two way off",
"readBy" : []
}
因此对于上述集合,我的输出应为
so for the above collection my output should be
[{
numberOfUnreadOffers: 4
}]
因为集合中有四个在readBy
数组中没有5add82620d7f5b38240c63d4
because four of the collection does not have 5add82620d7f5b38240c63d4
in readBy
array
推荐答案
您基本上使用 $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.
这篇关于计算值与数组不匹配的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!