niharika_neo
niharika_neo

Reputation: 8531

Mongo - How to leftpad values to a certain length?

We have a problem wherein certain strings appear as 123, 00123, 000123. We need to group by this field and we would like all the above to be considered as one group. I know the length of these values cannot be greater than 6.

The approach I was thinking was to left pad all of these fields in projection with 0s to a length of 6. One way would be to concat 6 0s first and then do a substr - but there is no length available for me to calculate the indexes for the substr method. -JIRA

Is there something more direct? Couldn't find anything here : https://docs.mongodb.org/manual/meta/aggregation-quick-reference/#aggregation-expressions or has anyone solved this some way?

Upvotes: 1

Views: 2197

Answers (1)

Alex Blex
Alex Blex

Reputation: 37048

I would convert then to int. E.g.:

For collection:

db.leftpad.insert([
    {key:"123"},
    {key:"0123"},
    {key:"234"},
    {key:"000123"}
])

counting:

db.leftpad.mapReduce(function(){
    emit(this.key * 1, 1);
}, function(key, count) {
    return Array.sum(count);
}, {out: { inline: 1 }}
).results

returns an array:

[
    {_id : 123, value : 3},
    {_id : 234, value : 1}
]   

If you can, it may worth to reduce it once:

db.leftpad.find({key:{$exists:true}, intKey:{$exists:false}}).forEach(function(d){
    db.leftpad.update({_id:d._id}, {$set:{intKey: d.key * 1}});
})

And then group by intKey.

Upvotes: 1

Related Questions