Max query in mongodb with where clause

538 Views Asked by At

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
2

There are 2 best solutions below

0
4J41 On BEST ANSWER

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"}
        }
    }
]);
0
Abdul Rehman Sayed On

If you are sure of the fact that your query will give you only a single record, You could use sort & limit to get your result like this one.

db.collection.find({P_id:"XYZ",experiment:'abc'}).sort({"bVal": -1}).limit(1)