我知道我需要输入以下内容
{ petrol: '$getdata.2020-07-30.91' }
其中addFields
问题在于日期部分根据当前日期而更改。
所以我有以下数据
{"_id":"5f216290b57c1e693fe1cc20","location":{"coordinates":[115.820539,-31.822072],"type":"Point"},"store":"Caltex Woolworths Greenwood","typeOfData":"fuelwatch","__v":0,"getdata":{"2020-07-30":[{"91":"1.02"},{"95":"1.15"},{"LPG":"0.90"},{"98":"1.22"}]}}
现在我需要做的是在获取时希望它可读。
const mFuel = require('mongoose').model('fuelwatch');
mFuel.aggregate(
[
{ "$geoNear": {
"near": {
"type": "Point",
"coordinates": [parseFloat(long), parseFloat(lat)]
},
"spherical": true,
"distanceField": "distance",
"distanceMultiplier": 0.000621371,
"maxDistance": 7 * 1609.34,
"includeLocs": "location"
}}
]
).exec(function (err, addocs) {
if(err){console.log(err)}
res.send(addocs);
});
上面的代码工作正常。
但是现在我需要移动日期{"2020-07-30":[{"91":"1.02"},{"95":"1.15"},{"LPG":"0.90"},{"98":"1.22"}]}
下的零件,以使它们看起来像这样
{"91":'1.02',"95":'1.15',"LPG":'0.90',"98":'1.22'}
,所以当我运行addocs["91"]
时,它将输出1.02。
我以前从未用过$addFields
这种方式
我尝试过
{ "$addFields": {
"petrol": {
"$filter": {
"input": [setKey],
"cond": {
"$eq": ["$getdata", "$$this.91"]
}
}
}
}}
但这没用。
完整代码:
var lat = req.params.lat;
var long = req.params.long;
var stationText;
var date = new Date();
const dateTimeFormat = new Intl.DateTimeFormat('en', { year: 'numeric', month: '2-digit', day: '2-digit' })
const [{ value: month },,{ value: day },,{ value: year }] = dateTimeFormat .formatToParts(date )
date = `${year}-${month}-${day }`
// console.log(`${day}-${month}-${year }`)
let setKey = `getdata.${date}`;
var fuelquery = {location:{$near: {$geometry: {type: "Point" ,coordinates: [ parseFloat(long), parseFloat(lat)]},$maxDistance: 5000,$minDistance: 0}}}
console.log(JSON.stringify(fuelquery));
//advertquery = { location:{ $geoWithin:{ $centerSphere: [ [ parseFloat(docs.location.coordinates[0]), parseFloat(docs.location.coordinates[1])], 10 / 6378.1] } } };
const mFuel = require('mongoose').model('fuelwatch');
mFuel.aggregate(
[
{ "$geoNear": {
"near": {
"type": "Point",
"coordinates": [parseFloat(long), parseFloat(lat)]
},
"spherical": true,
"distanceField": "distance",
"distanceMultiplier": 0.000621371,
"maxDistance": 7 * 1609.34,
"includeLocs": "location"
}},
{ "$addFields": {
"petrol": {
"$filter": {
"input": [setKey],
"cond": {
"$eq": ["$getdata", "$$this.91"]
}
}
}
}}
]
).exec(function (err, addocs) {
if(err){console.log(err)}
res.send(addocs);
});