获取集合中所有键的名称 [英] Get names of all keys in the collection

查看:63
本文介绍了获取集合中所有键的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取MongoDB集合中所有键的名称.

I'd like to get the names of all the keys in a MongoDB collection.

例如,从此:

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

我想获得唯一的密钥:

type, egg, hello

推荐答案

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

You could do this with 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:

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

这篇关于获取集合中所有键的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆