Last Updated: February 25, 2016
·
2.77K
· ketema

MongoDB: Describe a Collection & Search by date using default _id

I have been using mongodb for a little bit now and I came across two situations: 1) searching through a collection of documents that did not have an explicit timestamp field and 2) "describing" a collection. Here are the queries I came up with to solve these questions.

db.collection.find( {
    $where: "this._id.getTimestamp() > new Date('PROPER_DATE_FORMAT_HERE') &&
    this._id.getTimestamp() < new Date('PROPER_DATE_FORMAT_HERE')"
} );

The above query uses the fact that the default _id field generated by mongodb actually contains a time stamp within its first four bytes and can be compared against a Date object.

mr = db.runCommand({
    "mapreduce" : "collection", "map" : function() {
        for (var key in this) {
            emit(key, {type: typeof this[key]}); 
        }
    },
    "reduce" : function(key, types) {
        return types[0];
    },  "out": "types"
})

db[mr.result].find();

The above two commands work as a "describe" function on a collection. There is an assumption that the type of each field is the same across all the documents in the collection. I tried to use a "distinct" function to extract all the unique field types, but I was unable to figure out how to use that within the db.runCommand. Perhaps someone can improve it.

Here is the distinct function I came up with:

var distinct = function (arr) {
    var distinctArray = [];
    for (var i = 0; i < arr.length; i += 1) {
        if (distinctArray.indexOf(arr[i]) == -1) {
            distinctArray.push(arr[i]);
        }
    }
    return distinctArray;
}