3

我有一个结构如下的文档 -

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"
}
4

1 回答 1

4

使用mapReduce

记录对象:

> 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" } }

这不完全是你想要的,但它应该让你开始。

于 2012-07-05T13:56:33.390 回答