Search code examples
mongodbmongodb-queryaggregation-frameworkmongodb-aggregation

Max query in mongodb with where clause


I want create a MAX query in MongoDB with where clause.

I try this

db.Collection.aggregate({$group : {_id : "$P_ID", massi : {$max : "$b_val"}}},{P_ID:'XYZ',experiment:'abc'});

My WHERE clause is {P_ID:'XYZ',experiment:'abc'}

I don't why but this query don't work Obtain this error :

assert: command failed: {
    "ok" : 0,
    "errmsg" : "A pipeline stage specification object must contain          exactly one field.",
    "code" : 16435
} : aggregate failed
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:13:14
assert.commandWorked@src/mongo/shell/assert.js:287:5
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1312:5
@(shell):1:1

   2016-10-15T11:55:31.459+0200 E QUERY    [thread1] Error: command failed: {
        "ok" : 0,
        "errmsg" : "A pipeline stage specification object must contain     exactly one field.",
    "code" : 16435
} : aggregate failed :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:13:14
assert.commandWorked@src/mongo/shell/assert.js:287:5
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1312:5
@(shell):1:1

Solution

  • Where clause must be in a $match stage. Also, it is better have the pipeline as an array than separate arguments.

    The query must look like this.

    db.Collection.aggregate([
        {
            $match : {P_ID:'XYZ',experiment:'abc'}
        },
        {
            $group : {
                _id : "$P_ID", 
                massi : {$max : "$b_val"}
            }
        }
    ]);