Home > Back-end >  mongodb js easy sort method on the fly
mongodb js easy sort method on the fly

Time:11-26

I have the following output from the mongo shell :

mongos> var test=db.collection.stats().shards;for(key in test) printjson( key  " -> "  
 test[key].totalIndexSize)
"shard0_v2 -> 24782991360"
"shard4_v2 -> 36988542976"
"shard2_v2 -> 27401830400"
"shard3_v2 -> 21079486464"
"shard1_v2 -> 21052264448"
mongos> 

I need the output sorted as follow:

"shard0_v2 -> 24782991360"
"shard1_v2 -> 21052264448"
"shard2_v2 -> 27401830400"
"shard3_v2 -> 21079486464"
"shard4_v2 -> 36988542976"

Please, advice some quick and easy option in the mongo shell?

CodePudding user response:

You should definitely try to make an aggregation since the framework is done for this.

But if you want something that is quick and dirty:

Assuming:

test = {
          "shard0_v2": {
              "totalIndexSize": 24782991360 
          }, 
          //... others objects
      }

The solution would be:

Object.keys(test)
    .map((shardId) => {
        return `${shardId} -> ${test[shardId].totalIndexSize}`;
    })
    .sort()
    .forEach((line) => console.log(line))

CodePudding user response:

Thanks @mcanzerini , ended up with this:

 mongos> var x=[];var test=db.collection.stats().shards;for(key in test) x.push( 
key "->" test[key].totalIndexSize);x.sort()
[
    "shard0_v2->24783155200",
    "shard1_v2->36988542976",
    "shard2_v2->27401818112",
    "shard3_v2->21068120064",
    "shard4_v2->21080612864"
]
mongos>

Yours also work well:

mongos> var test=db.collection.stats().shards;Object.keys(test).map((shardId) => {return `${shardId} -> ${test[shardId].totalIndexSize}`;}).sort().forEach(function(line){print(line)})
shard0_v2 -> 24783155200
shard1_v2 -> 36988542976
shard2_v2 -> 27401818112
shard3_v2 -> 21071474688
shard4_v2 -> 21080666112
mongos>
  • Related