简体   繁体   English

在mongodb中,最简单的方法是从文档中获取单个字段的数组

[英]in mongodb, whats the easiest way to get an array of a single field from the documents

Assume, I have these documents in my collection: 假设我在我的收藏中有这些文件:

{
  _id: xxx,
  region: "sw"
},
{
  _id: yyy,
  region: "nw"
}

I want to end up with an array like this: 我想最终得到这样的数组:

['sw', 'nw']

I have tried mongodb aggregation/group and mapreduce but I always end up with an array of documents that then have to be looped through again to get to a single array. 我已经尝试了mongodb聚合/组和mapreduce,但我总是最终得到一个文档数组,然后必须再次循环才能获得单个数组。 Is there a way to achieve this in a single mongodb query or will it always require a query and then further processing? 有没有办法在单个mongodb查询中实现这一点,还是总是需要查询然后进一步处理?

Try this: 尝试这个:

db.foo.aggregate(
    {$group: {_id: null, region: {$push: "$region"}}}
).result[0].region

Or if you want to use map-reduce: 或者如果你想使用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

Or using group (thanks to @Travis for adding this one): 或使用组(感谢@Travis添加此组):

db.foo.group({
  reduce: function (curr, result) {
    result.regions.push(curr.region);
  },
  initial: { regions: [] }
})[0].regions

Note 注意

Using each of this methods you have to remember about BSON Document Size Limits 使用这些方法,您必须记住BSON文档大小限制

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 mongodb 中的子文档数组中获取单个字段 - Get a single field from a subdocument array in mongodb 用循环(Js)从数组中删除空值的最简单方法是什么 - Whats the easiest way to remove null values from an array with a loop (Js) 在2个React组件之间传递单个值的最简单方法是什么? - Whats the easiest way to pass a single value between 2 React components? 从mysql数据库制作动态折线图的最简单方法是什么? - Whats the easiest way to make a dynamic line graph from a mysql database? 从对象数组中获取所需键的最简单方法是什么 - What is the easiest way to get required keys from array of objects 从 Firestore 文档中读取字段的最简单方法 - Easiest way to read field from Firestore document 在一个字段中按数组查找mongodb中的文档? - finding documents in mongodb by array for one field? 在 Node.js 的 MongoDB 文档(带有 MongoClient)中附加一个数组字段,来自另一个字段 - Appending an array field, from another field, in MongoDB documents (with MongoClient) in Node.js 从多个文档中获取一个数组字段并将元素合并到一个object - Get an array field from multiple documents and merge elements into one object 有没有办法在 mongoDB 的嵌套数组中查找文档 - Is there a way to find documents in nested array in mongoDB
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM