I’m using MongoDB with NodeJS. I have a user database like the one below:
db.user.insertOne({
email: "user2@email.com",
name: "First Last",
age: 55,
analytics: [ { date: "2023-03-25", country: { UK: 1 }, browser: {}, os: {} },
{ date: "2023-03-26", country: {}, browser: {}, os: {} },
{ date: "2023-03-27", country: {}, browser: {}, os: {} },
{ date: "2023-03-28", country: {}, browser: {}, os: {} },
{ date: "2023-03-29", country: { UK: 1, AU: 5 }, browser: {}, os: {} },]}
);
Here is what I want to do:
I want to do a findOneAndUpdate
query. If today’s date exists in the analytics array, it will update the country, browser, and os field data. If the date does not exist inside the analytics array then it will create a new object like { date: "2023-03-25", country: { UK: 1 }, browser: { Opera: 1 }, os: { Windows: 1 } }
I tried doing queries like these, but it shows Updating the path 'analytics.$[element].country.UK' would create a conflict at 'analytics'
db.user.findOneAndUpdate(
{ email: "user2@email.com" },
{
$set: { "analytics.$[element].date": "2023-03-31", "analytics.$[element].country": {"UK": 1}, "analytics.$[element].browser": {"Opera": 1}, "analytics.$[element].os" : {"Windows": 1} },
$inc: { "analytics.$[element].country.UK": 1, "analytics.$[element].browser.Opera" : 1, "analytics.$[element].os.Windows" : 1 }
},
{
arrayFilters: [{ "element.date": "2023-03-30" }],
upsert: true,
returnOriginal: false
}
)
Is there any way to conditionally update this in a single findOneAndUpdate
query or using other methods?