mongo console:如何打印元素的内部类型

时间:2014-06-03 01:08:53

标签: mongodb mapreduce mongodb-query pymongo

使用$type和$ match,我可以反复发现Mongo认为我的数据有哪些类型。使用$not,我有时可以更快地得到结果。

有没有办法直接将project文件中的元素类型? (我认为我可以用pymongo得到它,但我还没看过那里。) 谢谢!

1 个答案:

答案 0 :(得分:1)

嗯,你可以用mapReduce来做这件事。我可以简单地演示,但复杂的结构需要更多的实现来实际通过递归工作。

所以给出了一份文件。

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")
}

你可以运行这个“基本”映射器:

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 } }
)

这给你输出如下:

"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"
        }
    }
],

您可以根据需要采用它,递归地转换为“数组”或“对象”(子文档)类型。但这是输出给定字段/属性的“类型”的一种方法。