我有格式的文件:
{
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查询实现相同的目标?
请注意,这有两个部分:
c
答案 0 :(得分:0)
使用Javascript重新整形map
函数中的文档:
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})
EDIT 2 使用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