N
N
nexcode2016-01-12 18:39:39
MongoDB
nexcode, 2016-01-12 18:39:39

Mongodb. How to leave the element with the maximum value in the array?

{
       "_id": 1,
       "values":[
          {
             "value1":10,
             "value2":12,
             "value3":30
          },
          {
             "value1":20,
             "value2":12,
             "value3":100
          },
          {
             "value1":30,
             "value2":14,
             "value3":50
          }
       ]
    }
    {
       "_id": 2,
       "values":[
          {
             "value1":10,
             "value2":12,
             "value3":60
          },
          {
             "value1":20,
             "value2":12,
             "value3":80
          },
          {
             "value1":30,
             "value2":14,
             "value3":70
          }
       ]
    }

I need to leave one document with one element in an array with the following criteria:
values.value1 = 20
    values.value2 = 12
    values.value3 максимальное значение из всех значений values.value3 во всех документах

For example, according to the above criteria, the following document should be obtained:
{
       "_id": 1,
       "values":[
          {
             "value1":20,
             "value2":12,
             "value3":100
          }
       ]
    }

Also, a solution that simply sorts documents and elements according to specified criteria is suitable. So that the first document is the one in which the value of values.value3 is the maximum possible and the first element in the array is the object with the maximum value. For example:
{
       "_id": 1,
       "values":[
         {
             "value1":20,
             "value2":12,
             "value3":100
          },
          {
             elements...
          }
       ]
    }
    {
       "_id": 2,
       "values":[
          {
             elements...
          }
       ]
    }

I can do this, but I use $match, $unwind, $group, $redact, $sort several times. Maybe someone will suggest a better implementation.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lega, 2016-01-13
@lega

I can do this, but I use
If this is a one-time operation, then everything is fine.
If frequent, then I would change the structure of documents so that modifying and reading documents are simple, fast commands.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question