是否可以在 MongoDB 中重写此 RQL 查询?

Is it possible to rewrite this RQL query in MongoDB?

我有以下格式的文档:

{
  a: "some-value",
  b: "some-other-value",
  c: {"subfield1": "val1", "subfield2": "val2", ..}
}

并希望使用 MongoDB:

生成看起来像这样的输出
{
  "some-value": {
    "some-other-value": {"subfield1": "val1", "subfield2": "val2"},
    ..
  }, 
  ..
}

在 RethinkDB 中,此查询有效:

r.table("some_table").getAll("some-value", "some-value-2",.., index: :some_index).map{ |d|
  r.object(
    d['a'],
      r.object(
        d['b'],
        d['c'].pluck("subfield1", "subfield2")
      )
    )
}.reduce{|left,right| left.merge(right)}.default({})

有没有一种方法可以使用 Mongo 查询实现相同的目的?

请注意,这有两个部分:

  1. 将所有结果映射到嵌套哈希
  2. 切片存储在字段 c
  3. 下的散列

map 函数中使用 Javascript 重塑文档:

db.collection.mapReduce(
    function(){
        emit(this._id, {
            [this.a]: {
                [this.b]: (({ subfield1, subfield2 }) => ({ subfield1, subfield2 }))(this.c)
            }
        });
    },
    function(){},
    {out: {inline: 1}}
).results.map(function(doc){return doc.value})

编辑 有点罗嗦:

db.collection.mapReduce(
    function(){
        emit(this._id, {
            [this.a]: {
                [this.b]: { subfield1: this.c.subfield1, subfield2: this.c.subfield2}
            }
        });
    },
    function(){},
    {out: {inline: 1}}
).results.map(function(doc){return doc.value})

编辑 2 return 作为单个对象使用 reduce 函数:

db.collection.mapReduce(
    function(){
        emit(null, {
            [this.a]: {
                [this.b]: (({ subfield1, subfield2 }) => ({ subfield1, subfield2 }))(this.c)
            }
        });
    },
    function(key, val){
        var res = {};
        val.forEach(function(doc) {
            // You may want to resolve conflicts here, if you have
            // more than 1 document with the same values for a and b.
            // In this code the later overwrites the former
            res = Object.assig(res, doc);
        });
        return res;
    },
    {out: {inline: 1}}
).results[0].value