MongoDB count distinct substrings of values

counting distinct values is easy as:

db.my_collection.distinct(_id)

but counting substrings of the values is not

var cnt=new Object()

db.my_collection.find({_id:{$exists:true}}).forEach(function(doc){if(doc._id != null && typeof doc._id == “string”) cnt[doc._id.substring(0,doc._id.indexOf(‘:’))]=1;})

var size=0;
for(key in cnt) {if (cnt.hasOwnProperty(key)) size++;};

This entry was posted in mongodb and tagged . Bookmark the permalink.

Leave a comment