1

你好我有这个json

db.people.insert({
    "ad" : "noc2",
    "createdDate" : ISODate(),
    "list" : [
            {
                    "id" : "p45",
                    "date" : ISODate("2014-01-01T12:18:30.568Z"),
                    "value3" : 21,
                    "value1" : 77,
                    "value2" : 489
            },
            {
                    "id" : "p6",
                    "date" : ISODate("2013-07-18T12:18:30.568Z"),
                    "value3" : 20,
                    "value1" : 20,
                    "value2" : 7
            },
            {
                   "id" : "4578",
                    "date" : ISODate("2013-07-18T12:18:30.568Z"),
                    "value3" : 21,
                    "value1" : 300,
                    "value2" : -319
            }
   ]

})

我想得到我的数组的最大值。例如,我想要一个这样的json:

“结果”:[{“_id”:“p45”,“价值”:587}]

我的总请求不起作用是: db.test1.aggregate({$match: "ad":"noc2"},{$unwind: '$list'},{$group: {_id: '$ad', list: {recommand: {$max: '$list'}}}});

4

2 回答 2

2

答案包含查询语法中的几个问题,但大多数情况下它都有效。您可以在下面找到固定查询:

db.people.aggregate(
  {$match:{ad:"noc2"}},
  {$unwind:"$list"},
  {$project:{_id:0, _id:"$list.id", "value":{$add:["$list.value1","$list.value2","$list.value3"]}}},
  {$sort:{value:-1}},
  {$limit:1}
);
于 2013-07-22T14:12:41.197 回答
1

尝试这个:

db.people.aggregate([
  {$match:{ad:"noc2"}},
  {$unwind:"$list"},
  {$project:{_id:0, _id":"$list.id", "value":{$add:["$list.value1","$list.value2","$list.value3"]}}},
  {$sort:{value:-1},
  {$limit:1}
])

输出:

{ "result" : [ { "_id" : "p45", "value" : 587 } ], "ok" : 1 }
于 2013-07-22T11:46:17.177 回答