简体   繁体   English

如何获取集合 MongoDB 中多个文档的单个字段值?

[英]How to fetch the single field value of multiple documents in a collection MongoDB?

I have a collection of documents with the following schema:我有一组具有以下架构的文档:

{ 
    "_id" : ObjectId("8dcaac2eb104c2133d66f144"), 
    "Shape" : "circle",  
    "Color" : "blue" 
},

My goal is to fetch the value of a specific field dynamically for a range of documents.我的目标是为一系列文档动态获取特定字段的值。 A response to a request of the Color value of 3 documents should look like this:对 3 个文档的颜色值请求的响应应如下所示:

{
    "blue"
    "green"
    "yellow"
}

I'm using Mongodb and nodejs, here's my code:我正在使用 Mongodb 和 nodejs,这是我的代码:

var field = req.params.field
var field_option = {};
field_option[field] = 1;

db.collection.find({_id: {$gte: first, $lt: last}}, field_option).toArray(function(err, data){
    if(err || !data) throw err;
    res.json(data);
});

However, the output is wrong:但是,output 是错误的:

[
    {
        "_id": "8dcaac2eb104c2133d66f144",
        "Shape" : "circle",  
        "Color" : "blue" 
    },
    {
        "_id": "8dcaac2eb104c2133d66f145",
        "Shape" : "square",  
        "Color" : "green" 
    },
    {
        "_id": "8dcaac2eb104c2133d66f146",
        "Shape" : "triangle",  
        "Color" : "yellow" 
    }

]

To get this as a response you have to manipulate the results after getting the data from mongo query.要将此作为响应,您必须在从 mongo 查询中获取数据后操作结果。

var data = res.json(data), endResult = [];
for(key in data) {
    endResult[key] = data[key]["Color"];
}
return endResult; 

The object you want is wrong你要的object是错的

{
  "blue"
  "green"
  "yellow"
}

You need manage the result in a array.您需要在数组中管理结果。

[
  "blu",
  "green",
  "yellow",
]

There 2 way using a agregate or manipulating the result有两种使用聚合或操纵结果的方法

1 way: 1种方式:

db.collection.aggregate([
  { $match: { _id: {$gte: first, $lt: last} }},
  { $group: { _id: "1", fields: { $push: { $concat: field }}}}
]);

it returns a object with the positions _id, and fields with the result.它返回带有位置_id 的 object 和带有结果的字段。 Because the pipeline of the aggregation do the match and after group by a defautl value and put into a array the field you want因为聚合的管道通过默认值进行匹配和分组,并将所需的字段放入数组中

2 way: Manipulating the result using a map. 2 方式:使用 map 操作结果。

db.collection.find({_id: {$gte: first, $lt: last}}, field_option).toArray(function(err, data){
    if(err || !data) throw err;
    res.json(data.map(item => (item[field]);
});

It returns the array you want, data is a array of object, and the function map is used to reestructure the object to a string.它返回你想要的数组,数据是一个 object 的数组,function map 用于重新构造 ZA8CFDE6331BD59EB2666CFDE63131ACBD59668CFDE63131ACBD4BEB6668CFDE63131ACBD5968 字符串。

The second way is easier than the first and impact less the code.第二种方法比第一种更容易,并且对代码的影响更小。

暂无
暂无

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

相关问题 如何在具有多个条件的 MongoDB 集合中的所有文档中求和键的值 - How to sum the value of a key across all documents in a MongoDB collection with multiple conditions 在现有集合(mongodb)的所有文档中添加字段? - Add a field in all documents in an existing collection (mongodb)? 将一个新字段添加到集合的所有文档中,将文档字段中的值添加到 MongoDB (Mongoose) 中,记录为 300K+ - Add a new field to all documents of a collection with the value from the document field into MongoDB (Mongoose) with records of 300K+ 如何从集合中的所有文档中获取集合中某个整数字段具有最高值的所有文档 - How to get all the documents within a collection that have the highest value for a certain integer field out of all documents in the collection 如何使用另一个集合中的字段值更新Mongodb集合中的文档 - How to update document in Mongodb collection with a field value from another collection 如何在一次查询中对mongodb中的多个字段和多个文档进行递增 - How to increment value in multiple fields and multiple documents in mongodb in one query 通过将value字段和集合名称作为参数传递给node js,无法从mongodb获取记录 - not able to fetch the record from mongodb by passing the value field and collection name as parameters in node js 如何在ejs中显示集合中的文档数量? 用 mongodb - How to display the amount of documents in a collection in ejs? With mongodb 如何列出子集合中的所有文档,然后通过他们的 ID 获取他们的文档? - How to list all documents in a sub-collection and then fetch their documents by their ID? mongodb - 按字段名的值查询文档 - mongodb - query documents by value of field name
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM