MongoDB:MapReduce ora这种查询的聚合框架?

时间:2014-11-12 14:26:15

标签: mongodb nosql

我的收藏中包含以下文件:

{
  "attr_a" : {
        "_id" : ObjectId("51877b939a9cd88730d6030e"),
        "key" : "a-key-1",
        "name" : "a name 1"    
    },

    "attr_b" : {
          "_id" : ObjectId("51877b9392lfd88730d602sw"),
          "key" : "b-key-1",
          "name" : "b name 2"    
      }

}


{
  "attr_a" : {
        "_id" : ObjectId("51877b939a9cd88730d6030e"),
        "key" : "a-key-2",
        "name" : "a name 2"    
    },

  "attr_b" : {
        "_id" : ObjectId("51877b9392lfd88730d602sw"),
        "key" : "b-key-2",
        "name" : "b name 2"    
    }

}

我想创建一个查询结果,例如:

{
  "attr_a" : [{
        "_id" : ObjectId("51877b939a9cd88730d6030e"),
        "key" : "a-key-1",
        "name" : "a name 1"    
    }, 
    {
          "_id" : ObjectId("51877b939a9cd88730d6030e"),
          "key" : "a-key-2",
          "name" : "a name 2"    
      }
    ],

"attr_b" : [{
      "_id" : ObjectId("51877b9392lfd88730d602sw"),
      "key" : "b-key-1",
      "name" : "b name 2"    
  }, 
  {
        "_id" : ObjectId("51877b9392lfd88730d602sw"),
        "key" : "b-key-2",
        "name" : "b name 2"    
  }]

}

我使用的是MongoDB 2.6.x和Spring Data 1.6.5,我试图弄清楚是否可以使用聚合框架或map-reduce完成(在这两种情况下都应该可以实时完成)或以其他不同方式完成。

或者我应该考虑引入Solr / Elastic Search?

有什么建议吗?

提前致谢, Alexio Cassani

1 个答案:

答案 0 :(得分:1)

您可以通过将整个集合分组到一个文档中来执行此操作,使用$push来汇编数组:

db.test.aggregate([{$group: {
    _id: null, 
    attr_a: {$push: '$attr_a'},
    attr_b: {$push: '$attr_b'}
}}])