MongoDB return last value using filter and grouping by variable

0

I have the following event being inserted into my MongoDB database

{
   _id:"5c0539158863a16a282917ad",
   owner:"clientX",
   source:"Deposito01",
   metric:"temperature",
   datetime:"2018-12-03T12:09:25.000Z",
   message:{
      temperature:"-0.250000",
      sensor:"sensor_0",
      device_id:"client_dep123_temp",
      local:"deposito_02",
      cliente:"clientX",
      awsRequestId:"xxxxx",
      datetime:"2018-12-03T12:09:25.000Z"
   }
}

I would like to return the last value of message.temperature , grouping it by field source , whenever the metric field is equal to "temperature".

I would like to learn how a "search" of this type is structured, if it is necessary to exemplify with a snippet of code, I am using python

    
asked by anonymous 03.12.2018 / 19:16

1 answer

0

I was able to solve my problem in the following way:

   reg = db.logs.aggregate([
        {'$match':  {'metric': 'temperature'}},
        {'$match':  {'owner': owner}},
        {'$sort':   {'datetime':-1}},
        {'$group':
            {'_id':'$source',
                'owner':    {'$first':'$owner'},
                'source':   {'$first':'$source'},
                'metric':   {'$first':'$metric'},
                'datetime': {'$first':'$datetime'},
                'message':  {'$first':'$message'}
            }
         }])
    
04.12.2018 / 19:15