计算值与数组不匹配的位置

时间:2018-05-07 08:51:32

标签: node.js mongodb mongoose mongodb-query aggregation-framework

我已关注offers集合

此处readBy包含用户的_id ... 现在我想计算userId = "5add82620d7f5b38240c63d4"

的unRead商品数量
{
    "_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
}]

因为5add82620d7f5b38240c63d4数组

中有四个集合没有readBy

1 个答案:

答案 0 :(得分:2)

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

var userId= "5add82620d7f5b38240c63d4";

Model.aggregate([
  { "$group": {
    "_id": null,
    "numberOfUnreadOffers": {
      "$sum": {
        "$cond": {
          "if": { 
            "$setIsSubset": [[mongoose.Types.ObjectId(userId)], "$readBy"]
          },
          "then": 0,
          "else": 1
        }
      }
    }
  }}
]) 

当然,您还需要使用“{1}}从”字符串“”转换为有效的mongoose.Types.ObjectId值。

但实际上,您可以通过简单的count()获得更好的效果:

ObjectId

所以你根本不应该使用Model.count({ "readBy": { "$ne": userId } })