mongodb 获取集合中所有键的名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2298870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get names of all keys in the collection
提问by Steve
I'd like to get the names of all the keys in a MongoDB collection.
我想获取 MongoDB 集合中所有键的名称。
For example, from this:
例如,从这里:
db.things.insert( { type : ['dog', 'cat'] } );
db.things.insert( { egg : ['cat'] } );
db.things.insert( { type : [] } );
db.things.insert( { hello : [] } );
I'd like to get the unique keys:
我想获得唯一键:
type, egg, hello
回答by kristina
You could do this with MapReduce:
你可以用 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"
})
Then run distinct on the resulting collection so as to find all the keys:
然后在结果集合上运行 distinct 以找到所有键:
db[mr.result].distinct("_id")
["foo", "bar", "baz", "_id", ...]
回答by James Cropcho
With Kristina's answeras inspiration, I created an open source tool called Variety which does exactly this: https://github.com/variety/variety
以Kristina 的回答为灵感,我创建了一个名为 Variety 的开源工具,它正是这样做的:https: //github.com/variety/variety
回答by Sagar Veeram
You can use aggregation with new $objectToArrray
in 3.4.4
version to convert all top key & value pair into document arrays followed by $unwind
& $group
with $addToSet
to get distinct keys across entire collection.
您可以使用聚合 with new $objectToArrray
in 3.4.4
version 将所有顶级键值对转换为文档数组,然后是$unwind
& $group
with$addToSet
以在整个集合中获取不同的键。
$$ROOT
for referencing the top level document.
$$ROOT
用于引用顶级文档。
db.things.aggregate([
{"$project":{"arrayofkeyvalue":{"$objectToArray":"$$ROOT"}}},
{"$unwind":"$arrayofkeyvalue"},
{"$group":{"_id":null,"allkeys":{"$addToSet":"$arrayofkeyvalue.k"}}}
])
You can use below query for getting keys in a single document.
您可以使用以下查询获取单个文档中的键。
db.things.aggregate([
{"$match":{_id: "5e8f968639bb8c67726686bc"}}, /* Replace with the document's ID */
{"$project":{"arrayofkeyvalue":{"$objectToArray":"$$ROOT"}}},
{"$project":{"keys":"$arrayofkeyvalue.k"}}
])
回答by Carlos LM
Try this:
尝试这个:
doc=db.thinks.findOne();
for (key in doc) print(key);
回答by Li Chunlin
If your target collection is not too large, you can try this under mongo shell client:
如果你的目标集合不是太大,你可以在 mongo shell 客户端下试试这个:
var allKeys = {};
db.YOURCOLLECTION.find().forEach(function(doc){Object.keys(doc).forEach(function(key){allKeys[key]=1})});
allKeys;
回答by Ingo Fischer
A cleaned up and reusable solution using pymongo:
使用 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')
Usage:
用法:
get_keys('dbname', 'collection')
>> ['key1', 'key2', ... ]
回答by Laizer
Using python. Returns the set of all top-level keys in the collection:
使用蟒蛇。返回集合中所有顶级键的集合:
#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()
)
回答by BobHy
Here is the sample worked in Python: This sample returns the results inline.
这是在 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']
回答by Ashh
If you are using mongodb 3.4.4 and above then you can use below aggregation using $objectToArray
and $group
aggregation
如果您使用的是 mongodb 3.4.4 及更高版本,那么您可以使用以下聚合 using$objectToArray
和$group
聚合
db.collection.aggregate([
{ "$project": {
"data": { "$objectToArray": "$$ROOT" }
}},
{ "$project": { "data": "$data.k" }},
{ "$unwind": "$data" },
{ "$group": {
"_id": null,
"keys": { "$addToSet": "$data" }
}}
])
Here is the working example
这是工作示例
回答by krishna Prasad
I am surprise, no one here has ans by using simple javascript
and Set
logic to automatically filter the duplicates values, simple example on mongo shellas below:
我很惊讶,这里没有人通过使用简单javascript
和Set
逻辑来自动过滤重复值,mongo shell上的简单示例如下:
var allKeys = new Set()
db.collectionName.find().forEach( function (o) {for (key in o ) allKeys.add(key)})
for(let key of allKeys) print(key)
This will print all possible unique keysin the collection name: collectionName.
这将打印集合名称中所有可能的唯一键:collectionName。