mongodb - Mongo:. How to get unique rows -


i have following object , record has keyword , deviceid.

there multiple object same deviceid. last entry each device id

{   search:{      keyword:"_"    },   datecreated:"",   device:[{     deviceid:"_"   }],  } 

example

{   search:{      keyword:"fl"    },   datecreated:"01/01/2017",   device:[{     deviceid:"1"   }],  }  {   search:{      keyword:"atl"    },   datecreated:"01/02/2017",   device:[{     deviceid:"1"   }],  } {   search:{      keyword:"ga"    },   datecreated:"01/03/2017",   device:[{     deviceid:"2"   }],  } 

the query should return

{   search:{      keyword:"atl"    },   datecreated:"01/02/2017",   device:[{     deviceid:"1"   }],  } {   search:{      keyword:"ga"    },   datecreated:"01/03/2017",   device:[{     deviceid:"2"   }],  } 

you can not achieve using "datecreated",first need convert "datecreated" column in date format(in context mongo iso date). after that, can run following achieving last entry mentioned in question

db.abc.aggregate([ { "$unwind": "$device"  },  {$group: {    _id: "$device",    search: {      "$max": "$search"    },    datecreated: {      "$max": "$datecreated"    }  }  } ]) 

and if looking same json format can project query,

db.abc.aggregate([   {     "$unwind": "$device"   },   {     $group: {       _id: "$device",       device: {         "$push": "$device"       },       search: {         "$max": "$search"       },       datecreated: {         "$max": "$datecreated"       }     }   },   {     $project: {       search: 1,       datecreated: 1,       device: 1,       _id: 0     }   } ]) 

Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -