1

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'}}}});

2 Answers 2

2

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}
);
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your response but if i have too much value, how i can to do without write all values in my array ? Because i can't to do this because i must keep the value name and his value, and the value name can change.Secondly, it may be that I have fifty thousand values
1

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 }

3 Comments

thanks for your response but if i have too much value, how i can to do without write all values in my array ?
Maybe it would be better to keep all of them into one array, something like "values": [21, 77, 489, ...] and then just sum them...
i can't to do this because i must keep the value name and his value, and the value name can change.Secondly, it may be that I have fifty thousand values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.