Home > database >  MongoDB aggregate, group and count in subdocuments
MongoDB aggregate, group and count in subdocuments

Time:12-24

I´m a bit stuck here... I have been following MongoDB Document:

{
    "_id": {
        "$oid": "63a3023e71a56a599007613b"
    },
    "image_uuid": "b9ff04d68b954ea390c8aa83644d5d08",
    "votes": {
    "42ceac05112d4092ad0d1f244a0016dd": {
        "created": {
            "$date": {
                "$numberLong": "1671627387000"
            }
        },
            "vote": "up"
        },
    "42ceac05112d4092ad0d1f244a0016de": {
        "created": {
            "$date": {
                "$numberLong": "1671627351000"
            }
        },
        "vote": "down"
        }
    }
}

Is there some way to group and count by "votes"? I´m only interested in the sum of all "up" and "down" in this document.

Thanks, Bastian

Tried every possible example found on Stackoverflow, but I´m quite new to MongoDB.

CodePudding user response:

Try this one:

db.collection.aggregate([
   { $set: { votes: { $objectToArray: "$votes" } } },
   {
      $project: {
         counts: {
            up: { $size: { $filter: { input: "$votes.v", cond: { $eq: ["$$this.vote", "up"] } } } },
            down: { $size: { $filter: { input: "$votes.v", cond: { $eq: ["$$this.vote", "down"] } } } }
         }
      }
   }
])

Mongo Playground

  • Related