Question

With $type and $match, I can find iteratively discover what types Mongo thinks my data has. With $not, I can get the results even faster sometimes.

Is there a way to project the type of an element in a document directly? (I presume I could get it with pymongo, but I haven't looked there yet.) thank you!

Was it helpful?

Solution

Well you could sort of do this with mapReduce. I can demonstrate for simplicity but complex structures would take more implementation to actually work through recursively.

So given a document.

db.team.find()
{
    "_id" : 50,
    "team_name" : "bulls",
    "players" : [
            {
                    "_id" : 100,
                    "player_name" : "Jokim"
            }
    ],
    "sub" : {
            "opt" : 1
    },
    "long" : NumberLong(123),
    "int" : 1,
    "bool" : false,
    "date" : ISODate("2014-06-03T01:42:01.016Z"),
    "unset" : null,
    "id" : ObjectId("538d36ccb88d0a9b6195ca66")
}

You could run this "basic" mapper:

db.team.mapReduce(
    function () {

        var obj = {};

        for ( var k in this ) {
            var type = ( this[k] != null ) 
                ? this[k].constructor.toString() : null;
            var match = null;
            if (type != null)
                match = type.match(/^function\s(\w+)/);

            obj[k] = ( match != null ) ? match[1]
                : ( type != null ) ? 'Object' : null;

        }

        emit( this._id, obj );

    },
    function(){},
    { "out": { "inline": 1 } }
)

Which gives you output like this:

"results" : [
    {
        "_id" : 50,
        "value" : {
            "_id" : "Number",
            "team_name" : "String",
            "players" : "Array",
            "sub" : "Object",
            "long" : "NumberLong",
            "int" : "Number",
            "bool" : "Boolean",
            "date" : "Date",
            "unset" : null,
            "id" : "ObjectId"
        }
    }
],

You can take that as far as you need, going recursively into "Array" or "Object" ( sub-document ) types. But that is one way to output a "type" for the given field/property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top