我能想到的實現這一點使用聚合查詢以下,但其非常靜態的唯一途徑。
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