Reputation: 800
hello i have this 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
}
]
})
and i'd like get a max value of my array. For example, i want a json as this :
"result" : [ { "_id" : "p45", "value" : 587 } ]
and my aggregate request who doesn't work is :
db.test1.aggregate({$match: "ad":"noc2"},{$unwind: '$list'},{$group: {_id: '$ad', list: {recommand: {$max: '$list'}}}});
Upvotes: 1
Views: 1788
Reputation: 4847
Try this:
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}
])
Output:
{ "result" : [ { "_id" : "p45", "value" : 587 } ], "ok" : 1 }
Upvotes: 1
Reputation: 516
The answer contains a couple of issues in query syntax, but mostly it works. Below you can find fixed query:
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}
);
Upvotes: 2