[英]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.