计算值与数组不匹配的地方

阿什

我有以下offers收藏

这里readBy包含的_id用户数量...现在,我要计算未读商品的数量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" : []
}

所以对于上面的集合我的输出应该是

[{
  numberOfUnreadOffers: 4
}]

因为集合四个没有5add82620d7f5b38240c63d4readBy

尼尔·伦恩

您基本上使用$setIsSubset$cond这里:

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

但实际上,您可以通过简单的操作获得更好的性能count()

Model.count({ "readBy": { "$ne": userId } })

因此,您真的不应该使用.aggregate()此功能。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章