我有一个像 -
这样的结构的文档Doc {
"DocName": "DocName",
"Array": [{
"Name": "Name1",
"Value": "Value1"
},{
"Name": "Name2",
"Value": "Value2"
},{
"Name": "Name3",
"Value": "Value3"
}]
}
是否可以查询Mongo,以便它以下面的格式返回多个文档?
{
DocName: "DocName",
Name: "Name1",
Value: "Value1"
},
{
DocName: "DocName",
Name: "Name2",
Value: "Value2"
},
{
DocName: "DocName",
Name: "Name3",
Value: "Value3"
}
答案 0 :(得分:4)
记录对象:
> db.doc.findOne();
{
"_id" : ObjectId("4ff5925327064149c3d7a31f"),
"docname" : "lorem",
"array" : [
{
"name" : "John",
"value" : "Blond"
},
{
"name" : "Eric",
"value" : "Brown"
}
]
}
地图功能:
map = function () {
var docname = this.docname;
this.array.forEach(function (item) {
emit(item, {'docname': docname});
});
}
减少功能
reduce = function(key, value) {
return value;
}
将它们整合在一起:
res = db.doc.mapReduce(map, reduce, { out: 'output' });
查询:
db.output.find();
结果:
{ "_id" : { "name" : "Eric", "value" : "Brown" }, "value" : { "docname" : "lorem" } }
{ "_id" : { "name" : "John", "value" : "Blond" }, "value" : { "docname" : "lorem" } }
这不完全是你想要的,但它应该让你开始。