使用where子句在mongodb中进行最大查询

时间:2016-10-15 10:04:27

标签: mongodb mongodb-query aggregation-framework mongodb-aggregation

我想在MongoDB中使用where子句创建一个MAX查询。

我试试这个

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

我的WHERE子句是{P_ID:'XYZ',experiment:'abc'}

我不是为什么但这个查询不起作用 获取此错误:

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 个答案:

答案 0 :(得分:0)

Where子句必须位于$match阶段。此外,最好将管道作为数组而不是单独的参数。

查询必须如下所示。

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

答案 1 :(得分:0)

如果您确定您的查询只会为您提供一条记录,您可以使用sort&限制得到这样的结果。

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