我能想到的实现这一点使用聚合查询以下,但其非常静态的唯一途径。
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" } }
我认为你需要使用'mapReduce'做到这一点。如果可能的话,做客户端可能会更好。 – JohnnyHK 2013-02-16 21:30:57
为什么不在检索文档时这么做? – WiredPrairie 2013-02-16 21:32:45
@WiredPrairie说什么。只需使用'toString()'。 – glortho 2013-02-16 22:05:02