我有一个看起来像这样的文件:
{
'id': 123,
'somekey': {
'x': [],
'y': [],
'z': [],
}
}
我想得到的结果为:
['x', 'y', 'z']
。实现这一目标的相关问题是什么?
答案 0 :(得分:3)
相关查询是通过 Map-Reduce 。以下mapreduce操作将使用somekey
子文档的所有键作为_id
值填充单独的集合:
var map = function() {
for (var key in this.somekey) {
emit(key, null);
}
},
reducer = function(key, stuff) { return null; }, /* or do reducer = function(key, stuff) { } since it's not doing anything */
mapreduce = db.runCommand({
"mapreduce": "collectionName",
"map": map,
"reduce": reducer,
"out": "someKeyCollectionKeys"
});
您可以通过在生成的集合上运行distinct来获取所有动态子文档键的列表:
db[mapreduce.result].distinct("_id")
<强>输出强>
[ "x", "y", "z" ]