コレクション内のすべてのキーの名前を取得する 質問する

コレクション内のすべてのキーの名前を取得する 質問する

MongoDB コレクション内のすべてのキーの名前を取得したいと思います。

たとえば、次のようになります。

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

一意のキーを取得したい:

type, egg, hello

ベストアンサー1

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

次に、結果のコレクションに対して distinct を実行して、すべてのキーを見つけます。

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

おすすめ記事