Rahul Kumar
Rahul Kumar

Reputation: 85

Unable to make the right query in Mongodb

I want to group by name then find the percentage of count of fill document to total document. The data is given below,here(fill:0 means not fill):-

{"name":"Raj","fill":0}
{"name":"Raj","fill":23}
{"name":"Raj","fill":0}
{"name":"Raj","fill":43}
{"name":"Rahul","fill":0}
{"name":"Rahul","fill":23}
{"name":"Rahul","fill":0}
{"name":"Rahul","fill":43}
{"name":"Rahul","fill":43}
{"name":"Rahul","fill":43}

Result :-

{
  "name":"Raj",
   fillcount:2,
   fillpercentagetototaldocument:50%  // 2 (fill count except 0 value )  divide by 4(total document for raj)
}
{
  "name":"Rahul",
   fillcount:4,
   fillpercentagetototaldocument:66%   // 4(fill count except 0 value )  divide by 6(total document for rahul)
}

Upvotes: 1

Views: 43

Answers (2)

Tom Slabbaert
Tom Slabbaert

Reputation: 22316

You want you use $group combined with a conditional count like so:

db.collection.aggregate([
  {
    $group: {
      _id: "$name",
      total: {
        $sum: 1
      },
      fillcount: {
        $sum: {
          $cond: [
            {
              $ne: [
                "$fill",
                0
              ]
            },
            1,
            0
          ]
        }
      }
    }
  },
  {
    $project: {
      _id: 0,
      name: "$_id",
      fillcount: 1,
      fillpercentagetototaldocument: {
        "$multiply": [
          {
            "$divide": [
              "$fillcount",
              "$total"
            ]
          },
          100
        ]
      }
    }
  }
])

Mongo Playground

Upvotes: 1

Kerschbaumer Stefan
Kerschbaumer Stefan

Reputation: 392

You can use mongos aggregation function to achieve that. example:

db.getCollection('CollectionName').aggregate([
      {
        $group: {
          _id: { name: '$name'},
          fillpercentagetototaldocument: { $sum: '$fill' },
          fillCount:{$sum:1}
        },
      },
      { $sort: { fillpercentagetototaldocument: -1 } },

    ]);

The result will look like this afterwards:

[
{
    "_id" : {
        "name" : "Rahul"
    },
    "fillpercentagetototaldocument" : 152,
    "fillCount" : 6.0
},
{
    "_id" : {
        "name" : "Raj"
    },
    "fillpercentagetototaldocument" : 66,
    "fillCount" : 4.0
}
]

Upvotes: 0

Related Questions