Reputation: 6810
I have data in this structure:
{
"_id": "5f212467b57c1e693fd89060",
"location":
{
"coordinates": [-31.802758, 115.837737],
"type": "Point"
},
"store": "Liberty Landsdale",
"__v": 0,
"getdata": [
{
"2020-07-30":
{"95": "1.14"}
},
{
"2020-07-30":
{"91": "1.02"}
}
]
}
However I want it to look like this
{
"_id": "5f212467b57c1e693fd89060",
"location": {
"coordinates": [-31.802758, 115.837737],
"type": "Point"
},
"store": "Liberty Landsdale",
"__v": 0,
"getdata": [
{
"2020-07-30":
[
{"95": "1.14"},
{"91": "1.02"}
]
}
]
}
I know the problem is the way I am inserting it into mongodb
mFuel.findOneAndUpdate(
{'store': t, 'location': [{coordinates: [lat, long], type: "Point"}]},
{$addToSet: {'getdata': {[d]: {[ftype]: p}}}}, {upsert: true},
function (err) {
if (err) {
console.log('ERROR when submitting round');
console.log(err);
}
});
I have tried $push
as well as set
and addToSet
I am wondering what is the correct way to achieve what am trying to do?
Upvotes: 1
Views: 21
Reputation: 22276
You can use $arrayFilters with $set
to achieve this:
let d = '2020-07-30';
let setKey = `getdata.$[elem].${d}`;
let arrayFiltersKey = `elem.${d}`;
let col = await mFuel.updateOne(
{
'store': t, 'location': [{coordinates: [lat, long], type: 'Point'}]
},
{
$addToSet: {
[setKey]: {[ftype]: p}
}
},
{
arrayFilters: [
{[arrayFiltersKey]: {$exists: true}},
]
});
Note that this cannot work with upsert
as the usage of arrayFilters
with it throws an error.
Regardless this data structure strikes me as odd, I would recommend you change it to something that's easier to work with.
either:
"getdata": [
{
k: "2020-07-30",
v: [{"95": "1.14"}]
}
]
Or
"getdata": {
"2020-07-30": [
{"95": "1.14"}
]
}
-------------- edit -------------------
With the second structure:
let d = '2020-07-30';
let setKey = `getdata.${d}`;
let col = await mFuel.updateOne(
{
'store': t, 'location': [{coordinates: [lat, long], type: 'Point'}]
},
{
$addToSet: {
[setKey]: {[ftype]: p}
}
},
{
upsert: true
});
Upvotes: 1