在mongodb中有多个id和sum的组

时间:2017-07-26 08:47:02

标签: mongodb group-by sum

{
            "_id" : ObjectId("59774aa87da165f360b0271a"),
            "createdDate" : ISODate("2017-07-25T13:42:00.000Z"),
            "sourceId" : ObjectId("000000000000000000000000"),
            "fanClubId" : ObjectId("59774aa87da165f360b02719"),
            "coins" : -500,
            "reasonId" : ObjectId("593500980b0cbbe593cd722c"),
            "userId" : ObjectId("597731d3ee99e33e1696de79")
        }

        {
            "_id" : ObjectId("59784c76e8288e1be6dace64"),
            "createdDate" : ISODate("2017-07-26T08:01:58.000Z"),
            "sourceId" : ObjectId("000000000000000000000000"),
            "fanClubId" : ObjectId("59784c76e8288e1be6dace63"),
            "coins" : -500,
            "reasonId" : ObjectId("593500980b0cbbe593cd722c"),
            "userId" : ObjectId("597731d3ee99e33e1696de79")
        }

        {
            "_id" : ObjectId("597734e376f9e53e0e52588a"),
            "createdDate" : ISODate("2017-07-25T12:09:07.000Z"),
            "sourceId" : ObjectId("000000000000000000000000"),
            "fanClubId" : ObjectId("000000000000000000000000"),
            "coins" : 5,
            "reasonId" : ObjectId("593501ff0b0cbbe593cd7236"),
            "userId" : ObjectId("597731d3ee99e33e1696de79")
        }

        db.getCollection('FanCoins').aggregate([{$group : {_id:{userId:ObjectId("597731d3ee99e33e1696de79"),
        reasonId:ObjectId("593500980b0cbbe593cd722c")},coins:{$sum : { $add: ["$coins"]}}}} ])

我使用此查询获取userId&硬币总和的结果。 reasonId,但我得到了userId的总和。如何在mongodb组中做到这一点。

0 个答案:

没有答案