【问题标题】:How to get keys of a field in a document in MongoDB如何在MongoDB中获取文档中字段的键
【发布时间】:2015-12-29 11:08:34
【问题描述】:

我有一个如下所示的文档:

{
    'id': 123,
    'somekey': {
        'x': [],
        'y': [],
        'z': [],
    }
}

我想得到结果为:
['x', 'y', 'z']。实现此目的的相关查询是什么?

【问题讨论】:

  • 也许使用mapReduce
  • mapReduce 仅适用于文档的键。但在这种情况下,'x'、'y'、'z' 是可变的
  • 你说的'x'、'y'、'z'是什么意思?你能详细说明一下吗?
  • 我自己都搞糊涂了。对不起,我找到了正确的答案。谢谢@user3100115

标签: json mongodb mongodb-query


【解决方案1】:

相关查询是通过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" ]

【讨论】:

  • 你可以做reducer = function(key, stuff) { },因为它什么也没做
  • @user3100115 为建议干杯! :)
猜你喜欢
  • 2014-11-12
  • 2022-08-24
  • 1970-01-01
  • 1970-01-01
  • 2022-11-24
  • 2014-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多