MongoDB aggregate count based on multiple query fields - (Multiple field count)

venkat.s

My collection will look this,

{
    "_id" : ObjectId("55c8bd1d85b83e06dc54c0eb"),
    "name" : "xxx",
    "salary" : 10000,
    "type" : "type1"
}
{
    "_id" : ObjectId("55c8bd1d85b83e06dc54c0eb"),
    "name" : "aaa",
    "salary" : 10000,
    "type" : "type2"
}
{
    "_id" : ObjectId("55c8bd1d85b83e06dc54c0eb"),
    "name" : "ccc",
    "salary" : 10000,
    "type" : "type2"
}

My query params will be coming as,

{salary=10000, type=type2}

so based on the query I need to fetch the count of above query params

The result should be something like this,

{ category: 'type1', count: 500 } { category: 'type2', count: 200 } { category: 'name', count: 100 }

Now I am getting count by hitting three different queries and constructing the result (or) server side iteration I can get the result.

Can anyone suggest or provide me good way to get above result

Blakes Seven

Your quesstion is not very clearly presented, but what it seems you wanted to do here was count the occurances of the data in the fields, optionally filtering those fields by the values that matches the criteria.

Here the $cond operator allows you to tranform a logical condition into a value:

db.collection.aggregate([
    { "$group": {
        "_id": null,
        "name": { "$sum": 1 },
        "salary": { 
            "$sum": { 
                "$cond": [
                    { "$gte": [ "$salary", 1000 ] },
                    1,
                    0
                ]
            }
        },
        "type": { 
            "$sum": { 
                "$cond": [
                    { "$eq": [ "$type", "type2" ] },
                    1,
                    0
                ]
            }
        }
    }}
])

All values are in the same document, and it does not really make any sense to split them up here as this is additional work in the pipeline.

{ "_id" : null, "name" : 3, "salary" : 3, "type" : 2 }

Otherwise in the long form, which is not very performant due to needing to make a copy of each document for every key looks like this:

db.collection.aggregate([
  { "$project": {
    "name": 1,
    "salary": 1,
    "type": 1,
    "category": { "$literal": ["name","salary","type"] }
  }},
  { "$unwind": "$category" },
  { "$group": {
    "_id": "$category",
    "count": {
      "$sum": {
        "$cond": [
          { "$and": [ 
            { "$eq": [ "$category", "name"] },
            { "$ifNull": [ "$name", false ] }
          ]},
          1,
          { "$cond": [
            { "$and": [
              { "$eq": [ "$category", "salary" ] },
              { "$gte": [ "$salary", 1000 ] }
            ]},
            1,
            { "$cond": [
              { "$and": [
                { "$eq": [ "$category", "type" ] },
                { "$eq": [ "$type", "type2" ] }
              ]},
              1,
              0
            ]}
          ]}
        ]
      }
    }
  }}
])

And it's output:

{ "_id" : "type",   "count" : 2 }
{ "_id" : "salary", "count" : 3 }
{ "_id" : "name",   "count" : 3 }

If your documents do not have uniform key names or otherwise cannot specify each key in your pipeline condition, then apply with mapReduce instead:

db.collection.mapReduce(
    function() {
        var doc = this;
        delete doc._id;

        Object.keys(this).forEach(function(key) {
          var value = (( key == "salary") && ( doc[key] < 1000 ))
              ? 0
              : (( key == "type" ) && ( doc[key] != "type2" ))
              ? 0
              : 1;

          emit(key,value);
        });
    },
    function(key,values) {
        return Array.sum(values);
    },
    {
        "out": { "inline": 1 }
    }
);

And it's output:

    "results" : [
            {
                    "_id" : "name",
                    "value" : 3
            },
            {
                    "_id" : "salary",
                    "value" : 3
            },
            {
                    "_id" : "type",
                    "value" : 2
            }
    ]

Which is basically the same thing with a conditional count, except that you only specify the "reverse" of the conditions you want and only for the fields you want to filter conditions on. And of course this output format is simple to emit as separate documents.

The same approach applies where to test the condition is met on the fields you want conditions for and return 1 where the condition is met or 0 where it is not for the summing the count.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

MongoDB aggregate count based on multiple query fields - (Multiple field count)

From Dev

Mongodb aggregate (count) on multiple fields simultaneously

From Dev

MongoDB - aggregate multiple fields in one query

From Dev

Linq query with GROUP BY on multiple fields, SUM and COUNT

From Dev

Linq query with GROUP BY on multiple fields, SUM and COUNT

From Dev

Query to count distict on a field on multiple tables not working

From Dev

Count of the result of a MongoDB aggregate query

From Dev

Obtain count of multiple Arrays in same MongoDB query

From Dev

SQL Count on Multiple Fields

From Dev

mongodb aggregate multiple nested fields

From Dev

Mongodb aggregate query help - grouping with multiple fields and converting to an array

From Dev

MongoDB, Multiple count (with $exists)

From Dev

MongoDB, Multiple count (with $exists)

From Dev

Find count of maximum consecutive records based on one field in Mongodb Query

From Dev

Find count of maximum consecutive records based on one field in Mongodb Query

From Dev

CodeIgniter query group and count values in multiple fields (same type)

From Dev

MySQL Selecting multiple fields with one query that uses COUNT(*)

From Dev

mongodb query child collection count in aggregate group

From Dev

Multiple COUNT(DISTINCT CAST(field AS DATE) in one query

From Dev

Multiple mongoose count() queries to a MongoDB

From Dev

MongoDB Aggregate group by multiple fields and get average

From Dev

Multiple Count based on value MYSQL

From Dev

Count rows based on multiple criteria

From Dev

SQL: count based on multiple columns

From Dev

Multiple count query in sequelize ORM

From Dev

Multiple variables with COUNT(URL) query

From Dev

mysql - multiple rows of COUNT query

From Dev

Getting multiple COUNT in 1 query

From Dev

count multiple columns in one query

Related Related

  1. 1

    MongoDB aggregate count based on multiple query fields - (Multiple field count)

  2. 2

    Mongodb aggregate (count) on multiple fields simultaneously

  3. 3

    MongoDB - aggregate multiple fields in one query

  4. 4

    Linq query with GROUP BY on multiple fields, SUM and COUNT

  5. 5

    Linq query with GROUP BY on multiple fields, SUM and COUNT

  6. 6

    Query to count distict on a field on multiple tables not working

  7. 7

    Count of the result of a MongoDB aggregate query

  8. 8

    Obtain count of multiple Arrays in same MongoDB query

  9. 9

    SQL Count on Multiple Fields

  10. 10

    mongodb aggregate multiple nested fields

  11. 11

    Mongodb aggregate query help - grouping with multiple fields and converting to an array

  12. 12

    MongoDB, Multiple count (with $exists)

  13. 13

    MongoDB, Multiple count (with $exists)

  14. 14

    Find count of maximum consecutive records based on one field in Mongodb Query

  15. 15

    Find count of maximum consecutive records based on one field in Mongodb Query

  16. 16

    CodeIgniter query group and count values in multiple fields (same type)

  17. 17

    MySQL Selecting multiple fields with one query that uses COUNT(*)

  18. 18

    mongodb query child collection count in aggregate group

  19. 19

    Multiple COUNT(DISTINCT CAST(field AS DATE) in one query

  20. 20

    Multiple mongoose count() queries to a MongoDB

  21. 21

    MongoDB Aggregate group by multiple fields and get average

  22. 22

    Multiple Count based on value MYSQL

  23. 23

    Count rows based on multiple criteria

  24. 24

    SQL: count based on multiple columns

  25. 25

    Multiple count query in sequelize ORM

  26. 26

    Multiple variables with COUNT(URL) query

  27. 27

    mysql - multiple rows of COUNT query

  28. 28

    Getting multiple COUNT in 1 query

  29. 29

    count multiple columns in one query

HotTag

Archive