简体   繁体   中英

mongodb find largest key inside an item in mongodb

I have a mongodb collection that has the following schema

{
  _id: ,
  data: {
       1: {
          values: ...
       },
       3: {
           values: ...
       }
       2: {
          values: ...
       }
   }
}

and I wanted to know if it would be possible to sort the items inside the data object or pick the highest values using core mongodb instead of retrieving them and sorting using javascript.

Please read @NeilLunn's comments to the question first

The "possible" yet "impractical" pipeline could be like following:

db.collection.aggregate([
    {$project: {
        data: { $objectToArray: "$data" }
    }}, 
    {$unwind: "$data"},
    {$sort: {_id:1, "data.k":-1}},
    {$group: {_id:"$_id", data:{$first:"$data"}}},
    {$group: {_id:"$_id", data:{$push:"$data"}}},
    {$project: {
        _id: 1,
        data: { $arrayToObject: "$data" }            
    }}
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM