2013-02-16 60 views
1

我正在编写一个应用程序来使用Mongo数据库中的数据,但我需要以平面格式处理数据。我的文档中有几个数组,我想把它变成一个字符串数组,但是找不到用mongo查询的方法。Mongo Join String Array

文件:

{ 
    name: 'Hello World', 
    tags: ['simple', 'easy'] 
} 

所需的输出:

{ 
    name: 'Hello World', 
    tags: 'simple,easy', 
} 
+0

我认为你需要使用'mapReduce'做到这一点。如果可能的话,做客户端可能会更好。 – JohnnyHK 2013-02-16 21:30:57

+1

为什么不在检索文档时这么做? – WiredPrairie 2013-02-16 21:32:45

+0

@WiredPrairie说什么。只需使用'toString()'。 – glortho 2013-02-16 22:05:02

回答

0

我能想到的实现这一点使用聚合查询以下,但其非常静态的唯一途径。

db.test.aggregate([ 
    { $unwind: "$tags" }, 
    { $group: { _id: "$_id", name: {$first: "$name"}, firstTag: {$first: "$tags"}, lastTag: {$last: "$tags"} } }, 
    { $project: { name: "$name", tags: { $concat: [ "$firstTag", ",", "$lastTag" ] } } } 
]); 

但是,您可以用MapReduce的实现这一目标:

db.test.mapReduce(
    function() {emit(this._id, this);}, 
    function(key, value) {return value}, { 
     out:"tags", 
     finalize: function(key, reducedVal){ 
      reducedVal.tags = reducedVal.tags.join(); 
      return reducedVal; 
     } 
    } 
) 

> db.tags.find() 
{ "_id" : ObjectId("5849a9f6a4db9c5811299d08"), "value" : { "name" : "Hello World", "tags" : "simple,easy" } }