我想得到的名称所有的钥匙,在MongoDB收集。

例如,从这一点:

db.things.insert( { type : ['dog', 'cat'] } );
db.things.insert( { egg : ['cat'] } );
db.things.insert( { type : [] } );
db.things.insert( { hello : []  } );

我想得到的唯一的钥匙:

type, egg, hello
有帮助吗?

解决方案

您可以用MapReduce的做到这一点:

mr = db.runCommand({
  "mapreduce" : "my_collection",
  "map" : function() {
    for (var key in this) { emit(key, null); }
  },
  "reduce" : function(key, stuff) { return null; }, 
  "out": "my_collection" + "_keys"
})

然后运行对所得集合不同,以便发现所有的键:

db[mr.result].distinct("_id")
["foo", "bar", "baz", "_id", ...]

其他提示

克里斯蒂娜的回答 作为灵感,我创建了一个开放源工具,称为各种其不正是这样的: https://github.com/variety/variety

你可以使用聚集新的 $objectToArrray3.4.4 版本的转换所有顶级的关键的和价值对成文件阵列,随后通过 $unwind & $group $addToSet 获得不同的钥匙整个集合。

$$ROOT 为引用的顶级的文件。

db.things.aggregate([
  {"$project":{"arrayofkeyvalue":{"$objectToArray":"$$ROOT"}}},
  {"$unwind":"$arrayofkeyvalue"},
  {"$group":{"_id":null,"allkeys":{"$addToSet":"$arrayofkeyvalue.k"}}}
])

你可以用下面的查询获得的钥匙在一个单一的文件。

db.things.aggregate([
  {"$project":{"arrayofkeyvalue":{"$objectToArray":"$$ROOT"}}},
  {"$project":{"keys":"$arrayofkeyvalue.k"}}
])

尝试这种情况:

doc=db.thinks.findOne();
for (key in doc) print(key);

如果您的目标集合不是太大,你可以试试这个蒙戈下壳客户端:

var allKeys = {};

db.YOURCOLLECTION.find().forEach(function(doc){Object.keys(doc).forEach(function(key){allKeys[key]=1})});

allKeys;

使用Python。返回集集合中的所有顶级密钥:

#Using pymongo and connection named 'db'

reduce(
    lambda all_keys, rec_keys: all_keys | set(rec_keys), 
    map(lambda d: d.keys(), db.things.find()), 
    set()
)

下面是在Python工作的样品: 该样品内联返回结果。

from pymongo import MongoClient
from bson.code import Code

mapper = Code("""
    function() {
                  for (var key in this) { emit(key, null); }
               }
""")
reducer = Code("""
    function(key, stuff) { return null; }
""")

distinctThingFields = db.things.map_reduce(mapper, reducer
    , out = {'inline' : 1}
    , full_response = True)
## do something with distinctThingFields['results']

一个使用pymongo清理和可重复使用的解决方案:

from pymongo import MongoClient
from bson import Code

def get_keys(db, collection):
    client = MongoClient()
    db = client[db]
    map = Code("function() { for (var key in this) { emit(key, null); } }")
    reduce = Code("function(key, stuff) { return null; }")
    result = db[collection].map_reduce(map, reduce, "myresults")
    return result.distinct('_id')

用法:

get_keys('dbname', 'collection')
>> ['key1', 'key2', ... ]

如果您使用的是mongodb3.4.4及以上然后你可以用下面的聚合使用 $objectToArray$group 聚集

db.collection.aggregate([
  { "$project": {
    "data": { "$objectToArray": "$$ROOT" }
  }},
  { "$project": { "data": "$data.k" }},
  { "$unwind": "$data" },
  { "$group": {
    "_id": null,
    "keys": { "$addToSet": "$data" }
  }}
])

这里是工作

这正常工作对我说:

var arrayOfFieldNames = [];

var items = db.NAMECOLLECTION.find();

while(items.hasNext()) {
  var item = items.next();
  for(var index in item) {
    arrayOfFieldNames[index] = index;
   }
}

for (var index in arrayOfFieldNames) {
  print(index);
}

我惊讶的是,这里没有人具有通过使用简单javascriptSet逻辑自动过滤重复的值,在简单的例子ANS的蒙戈壳如下:

var allKeys = new Set()
db.collectionName.find().forEach( function (o) {for (key in o ) allKeys.add(key)})
for(let key of allKeys) print(key)

这将打印所有可能的独特的集合名称:集合名

要获得所有按键减去_id的列表,请考虑运行下面的总管道:

var keys = db.collection.aggregate([
    { "$project": {
       "hashmaps": { "$objectToArray": "$$ROOT" } 
    } }, 
    { "$project": {
       "fields": "$hashmaps.k"
    } },
    { "$group": {
        "_id": null,
        "fields": { "$addToSet": "$fields" }
    } },
    { "$project": {
            "keys": {
                "$setDifference": [
                    {
                        "$reduce": {
                            "input": "$fields",
                            "initialValue": [],
                            "in": { "$setUnion" : ["$$value", "$$this"] }
                        }
                    },
                    ["_id"]
                ]
            }
        }
    }
]).toArray()[0]["keys"];

我认为最好的方式做到这一点提到是mongod的3.4.4+,但没有使用$unwind操作href="https://stackoverflow.com/a/43570730/3100115">并使用管道只有两个阶段。相反,我们可以使用 $mergeObjects 和的 $objectToArray 运算符。

$group阶段,我们使用$mergeObjects算哪里键/值是从集合中的所有文档返回一个单一的文件。

然后是在这里我们使用$project$map返回键$objectToArray

let allTopLevelKeys =  [
    {
        "$group": {
            "_id": null,
            "array": {
                "$mergeObjects": "$$ROOT"
            }
        }
    },
    {
        "$project": {
            "keys": {
                "$map": {
                    "input": { "$objectToArray": "$array" },
                    "in": "$$this.k"
                }
            }
        }
    }
];

现在,如果我们有一个嵌套的文件,并想拿到钥匙为好,这是可行的。为了简单起见,让考虑一个文档通过简单的嵌入的文档看起来像这样:

{field1: {field2: "abc"}, field3: "def"}
{field1: {field3: "abc"}, field4: "def"}

下面的管道产量的所有密钥(FIELD1,FIELD2,字段3,字段4)。

let allFistSecondLevelKeys = [
    {
        "$group": {
            "_id": null,
            "array": {
                "$mergeObjects": "$$ROOT"
            }
        }
    },
    {
        "$project": {
            "keys": {
                "$setUnion": [
                    {
                        "$map": {
                            "input": {
                                "$reduce": {
                                    "input": {
                                        "$map": {
                                            "input": {
                                                "$objectToArray": "$array"
                                            },
                                            "in": {
                                                "$cond": [
                                                    {
                                                        "$eq": [
                                                            {
                                                                "$type": "$$this.v"
                                                            },
                                                            "object"
                                                        ]
                                                    },
                                                    {
                                                        "$objectToArray": "$$this.v"
                                                    },
                                                    [
                                                        "$$this"
                                                    ]
                                                ]
                                            }
                                        }
                                    },
                                    "initialValue": [

                                    ],
                                    "in": {
                                        "$concatArrays": [
                                            "$$this",
                                            "$$value"
                                        ]
                                    }
                                }
                            },
                            "in": "$$this.k"
                        }
                    }
                ]
            }
        }
    }
]

通过一个小的努力,我们可以得到在阵列字段,其中的元素是目的以及对于所有的子文档的密钥。

我是想在对的NodeJS编写终于想出了这一点:

db.collection('collectionName').mapReduce(
function() {
    for (var key in this) {
        emit(key, null);
    }
},
function(key, stuff) {
    return null;
}, {
    "out": "allFieldNames"
},
function(err, results) {
    var fields = db.collection('allFieldNames').distinct('_id');
    fields
        .then(function(data) {
            var finalData = {
                "status": "success",
                "fields": data
            };
            res.send(finalData);
            delteCollection(db, 'allFieldNames');
        })
        .catch(function(err) {
            res.send(err);
            delteCollection(db, 'allFieldNames');
        });
 });

读取新创建的集合 “allFieldNames” 后,将其删除。

db.collection("allFieldNames").remove({}, function (err,result) {
     db.close();
     return; 
});

作为每mongoldb 文档distinct的组合

  

查找用于跨单个集合或视图并返回结果在数组中的指定字段中的不同的值。

指标收集操作是什么会回来对于给定的键,或者索引的所有可能的值:

  

返回保存的标识和描述在收集现有索引的文档的列表的阵列

因此,在一个给定的方法,一个可以做使用类似以下的方法,以便查询集合了所有它的注册索引和回报,说与键索引对象(本例使用异步/指日可待的NodeJS,但很明显,你可以使用任何其他异步方法):

async function GetFor(collection, index) {

    let currentIndexes;
    let indexNames = [];
    let final = {};
    let vals = [];

    try {
        currentIndexes = await collection.indexes();
        await ParseIndexes();
        //Check if a specific index was queried, otherwise, iterate for all existing indexes
        if (index && typeof index === "string") return await ParseFor(index, indexNames);
        await ParseDoc(indexNames);
        await Promise.all(vals);
        return final;
    } catch (e) {
        throw e;
    }

    function ParseIndexes() {
        return new Promise(function (result) {
            let err;
            for (let ind in currentIndexes) {
                let index = currentIndexes[ind];
                if (!index) {
                    err = "No Key For Index "+index; break;
                }
                let Name = Object.keys(index.key);
                if (Name.length === 0) {
                    err = "No Name For Index"; break;
                }
                indexNames.push(Name[0]);
            }
            return result(err ? Promise.reject(err) : Promise.resolve());
        })
    }

    async function ParseFor(index, inDoc) {
        if (inDoc.indexOf(index) === -1) throw "No Such Index In Collection";
        try {
            await DistinctFor(index);
            return final;
        } catch (e) {
            throw e
        }
    }
    function ParseDoc(doc) {
        return new Promise(function (result) {
            let err;
            for (let index in doc) {
                let key = doc[index];
                if (!key) {
                    err = "No Key For Index "+index; break;
                }
                vals.push(new Promise(function (pushed) {
                    DistinctFor(key)
                        .then(pushed)
                        .catch(function (err) {
                            return pushed(Promise.resolve());
                        })
                }))
            }
            return result(err ? Promise.reject(err) : Promise.resolve());
        })
    }

    async function DistinctFor(key) {
        if (!key) throw "Key Is Undefined";
        try {
            final[key] = await collection.distinct(key);
        } catch (e) {
            final[key] = 'failed';
            throw e;
        }
    }
}

所以查询的集合与所述基本_id索引,将返回以下(测试集合只具有在测试时一个文档):

Mongo.MongoClient.connect(url, function (err, client) {
    assert.equal(null, err);

    let collection = client.db('my db').collection('the targeted collection');

    GetFor(collection, '_id')
        .then(function () {
            //returns
            // { _id: [ 5ae901e77e322342de1fb701 ] }
        })
        .catch(function (err) {
            //manage your error..
        })
});

你要知道,这里采用的方法,原产于驱动程序的NodeJS。由于一些其他的答案建议,还有其他的方法,如总框架。我个人觉得这个方法比较灵活,你可以轻松地创建和微调如何返回结果。显然,这只能满足顶级属性,没有嵌套的。 此外,为了保证所有的文件被表示应该有二级索引(除主_id一个其它),这些索引应设置为required

也许稍微偏离主题,但你可以递归漂亮地打印所有键/对象的字段:

function _printFields(item, level) {
    if ((typeof item) != "object") {
        return
    }
    for (var index in item) {
        print(" ".repeat(level * 4) + index)
        if ((typeof item[index]) == "object") {
            _printFields(item[index], level + 1)
        }
    }
}

function printFields(item) {
    _printFields(item, 0)
}

有用当一个集合中的所有对象具有相同的结构。

我们可以通过使用蒙戈js文件实现这一目标。添加下面的代码在 getCollectionName.js 下面给出文件并运行JS在Linux中的控制台文件:

  

<强>蒙戈--host 192.168.1.135 getCollectionName.js

db_set = connect("192.168.1.135:27017/database_set_name"); // for Local testing
// db_set.auth("username_of_db", "password_of_db"); // if required

db_set.getMongo().setSlaveOk();

var collectionArray = db_set.getCollectionNames();

collectionArray.forEach(function(collectionName){

    if ( collectionName == 'system.indexes' || collectionName == 'system.profile' || collectionName == 'system.users' ) {
        return;
    }

    print("\nCollection Name = "+collectionName);
    print("All Fields :\n");

    var arrayOfFieldNames = []; 
    var items = db_set[collectionName].find();
    // var items = db_set[collectionName].find().sort({'_id':-1}).limit(100); // if you want fast & scan only last 100 records of each collection
    while(items.hasNext()) {
        var item = items.next(); 
        for(var index in item) {
            arrayOfFieldNames[index] = index;
        }
    }
    for (var index in arrayOfFieldNames) {
        print(index);
    }

});

quit();

<强>感谢@ackuser

在从@詹姆斯Cropcho的回答线程,我降落在我发现超级好用以下。它是一个二进制工具,这正是我一直在寻找: mongoeye

使用这个工具,花了约2分钟,让我的模式在命令行出口。

我扩展卡洛斯LM的溶液中的位,所以它更详细说明。

的模式的示例:

var schema = {
    _id: 123,
    id: 12,
    t: 'title',
    p: 4.5,
    ls: [{
            l: 'lemma',
            p: {
                pp: 8.9
            }
        },
         {
            l: 'lemma2',
            p: {
               pp: 8.3
           }
        }
    ]
};

类型到控制台:

var schemafy = function(schema, i, limit) {
    var i = (typeof i !== 'undefined') ? i : 1;
    var limit = (typeof limit !== 'undefined') ? limit : false;
    var type = '';
    var array = false;

    for (key in schema) {
        type = typeof schema[key];
        array = (schema[key] instanceof Array) ? true : false;

        if (type === 'object') {
            print(Array(i).join('    ') + key+' <'+((array) ? 'array' : type)+'>:');
            schemafy(schema[key], i+1, array);
        } else {
            print(Array(i).join('    ') + key+' <'+type+'>');
        }

        if (limit) {
            break;
        }
    }
}

执行命令

schemafy(db.collection.findOne());

输出

_id <number>
id <number>
t <string>
p <number>
ls <object>:
    0 <object>:
    l <string>
    p <object>:
        pp <number> 

我有1个简单的解决办法...

你所能做的就是在插入数据/文件到您的主要收藏“东西”,你必须在1个单独收集插入的属性可以说“things_attributes”。

所以每次你在“事”插入时,你就从“things_attributes”如果有新的密钥存在该文件中追加再次比较该文件的值与您的新文档的密钥,并获得重新插入。

所以things_attributes将只有1唯一键的文件,该文件时,你永远需要使用就可以轻松搞定findOne()

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top