获取集合中所有键的名称

16 浏览
0 Comments

获取集合中所有键的名称

我想获得MongoDB集合中所有键的名称。

例如,从这个例子中:

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

我想获得唯一的键:

type, egg, hello

admin 更改状态以发布 2023年5月21日
0
0 Comments

Kristina的回答的启示下,我创建了一个开源工具,名为Variety,它正是做这个的:https://github.com/variety/variety

0
0 Comments

\n\n你可以使用MapReduce实现这个操作:\n

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"
})

\n然后在结果集上运行distinct,以找到所有的键:\n

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

0