Mongodb return last value using filter and grouping by variable

Asked

Viewed 43 times

0

I have the following event being inserted into my Mongodb base

{
   _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 by the field source, whenever the countryside metric 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 code snippet, I am using python

1 answer

0

I managed to solve my problem as follows:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.