[英]in mongodb, whats the easiest way to get an array of a single field from the documents
假設我在我的收藏中有這些文件:
{
_id: xxx,
region: "sw"
},
{
_id: yyy,
region: "nw"
}
我想最終得到這樣的數組:
['sw', 'nw']
我已經嘗試了mongodb聚合/組和mapreduce,但我總是最終得到一個文檔數組,然后必須再次循環才能獲得單個數組。 有沒有辦法在單個mongodb查詢中實現這一點,還是總是需要查詢然后進一步處理?
嘗試這個:
db.foo.aggregate(
{$group: {_id: null, region: {$push: "$region"}}}
).result[0].region
或者如果你想使用map-reduce:
db.foo.mapReduce(
function() { emit(null, this.region)},
function(key, values) {
result = {region: []};
values.forEach(function(x){ result.region.push(x); });
return result;
},
{out: {inline: 1}}
).results[0].value.region
或使用組(感謝@Travis添加此組):
db.foo.group({
reduce: function (curr, result) {
result.regions.push(curr.region);
},
initial: { regions: [] }
})[0].regions
注意
使用這些方法,您必須記住BSON文檔大小限制
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.