代码之家  ›  专栏  ›  技术社区  ›  SCO

Mongoose count使用聚合嵌入数组元素

  •  0
  • SCO  · 技术社区  · 6 年前

    {
        "_id" : ObjectId("578caba0264f76ec80d87e7c"),
        "issuer" : ObjectId("578c9c68261246f717343ab7"),
        "messages" : [
            {
                "content" : "Hi !",
                "type" : "text",
                "user" : ObjectId("56582b17b380912011c485e2"),
                "_id" : ObjectId("578caba08cf9a9081927e326"),
                "createdAt" : ISODate("2016-07-18T10:12:48.778Z"),
                "seenAt" : ISODate("2016-07-18T10:13:16.725Z")
            },
            {
                "content" : "Wassup ?",
                "type" : "text",
                "user" : ObjectId("569a9d343bd9840e26797412"),
                "_id" : ObjectId("578cabcb8cf9a9081927e327"),
                "createdAt" : ISODate("2016-07-18T10:13:31.254Z"),
                "seenAt" : ISODate("2016-07-18T10:13:34.133Z")
            },
            {
                "content" : "Fine, ya ?",
                "type" : "text",
                "user" : ObjectId("569a9d343bd9840e26797412"),
                "_id" : ObjectId("578cabd38cf9a9081927e328"),
                "createdAt" : ISODate("2016-07-18T10:13:39.573Z")
            }
        }
    }
    

    到目前为止,我尝试使用猫鼬聚合:

    function findUnreadByIssuerId(issuerId) {
        return Conversation
        .aggregate()
        .match({ issuer: issuerId })
        .unwind('messages')
        .match({'messages.seenAt' : { $exists: 'false'} })
        .count()
        .exec();
    }
    

    这里的要点是nodejs抱怨count()不是一个函数。聚合在其他方面似乎没有问题,因为如果删除count(),就会得到一个数组。

    然后,我尝试使用$group,但我是Mongo及其分组的新手,我得到了一个空数组:

    return Conversation .aggregate([
        { $match: { issuer: issuerId } },
        { $unwind: '$messages' },
        { $match: {'messages.seenAt' : { $exists: 'false'} } },
        { $group: {
            _id: '$messages.createdAt',
            count: { $sum: 1 }
        }}
        ])
        .exec();
    

    在提供的示例中,调用的预期结果理想情况下为2。但是我能处理{sum:2}虽然不理想。我的猫鼬聚合链有什么问题?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Mazki516    6 年前

    对于Mongo>=3.4:

    https://docs.mongodb.com/manual/reference/operator/aggregation/count/

    像这样使用它:

    .count("total_unseen")

    {total_unseen: 1}

    对于Mongo<3.4

    使用$group和count:

    { $group: null, count: {$sum: 1} }
    

    如果管道中的一个阶段为空,结果将为空,但通常驱动程序正在转换为更合适的值。