加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

mongodb python获取到集合中所有键的名字(get all keys)

发布时间:2020-12-13 12:39:41 所属栏目:百科 来源:网络整理
导读:想要获取mongodb集合中所有的键名字 如: db.things.insert(?{?type?:?['dog',?'cat']?}?);db.things.insert(?{?egg?:?['cat']?}?);db.things.insert(?{?type?:?[]?}?);db.things.insert(?{?hello?:?[]??}?); 获取到所有的键名: type,?egg,?hello 代码如下

想要获取mongodb集合中所有的键名字

如:

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

获取到所有的键名:

type,?egg,?hello

代码如下:

from?pymongo?import?MongoClient
from?bson?import?Code

def?get_keys(db,?collection):
????#?db?mongodb的集合
????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')

参考:https://stackoverflow.com/questions/2298870/get-names-of-all-keys-in-the-collection

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读