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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 11:42:01  来源:igfitidea点击:

Get names of all keys in the collection

mongodbmongodb-queryaggregation-framework

提问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 $objectToArrrayin 3.4.4version to convert all top key & value pair into document arrays followed by $unwind& $groupwith $addToSetto get distinct keys across entire collection.

您可以使用聚合 with new $objectToArrrayin 3.4.4version 将所有顶级键值对转换为文档数组,然后是$unwind& $groupwith$addToSet以在整个集合中获取不同的键。

$$ROOTfor 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 $objectToArrayand $groupaggregation

如果您使用的是 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 javascriptand Setlogic to automatically filter the duplicates values, simple example on mongo shellas below:

我很惊讶,这里没有人通过使用简单javascriptSet逻辑来自动过滤重复值,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