Answer the question
In order to leave comments, you need to log in
How to use $and operator to update mongoDB?
There is a condition for adding data, the value must be greater than the existing one, then all other fields are changed. How to do it? In my case, all fields change anyway, and only the price field changes depending on $max. It would be nice if there was a $and operator for Mongo Update but couldn't find
User.updateOne(
{id: 1},
{
$set: { 'stats.one': r.one, 'stats.openDate': new Date() },
$max: { 'stats.price': r.price }
},
{ "upsert": true },
(err, data) => console.log(data)
)
Answer the question
In order to leave comments, you need to log in
In this case, it is enough to use the aggregation syntax for updating, so you can use the conditions for adding.
User.updateOne(
{id: 1},
[{
$set: {
'stats.price': {
$cond: {
if: {$gt: [r.price, '$stats.price']},
then: r.price,
else: '$stats.price'
}
},
'stats.one': {
$cond: {
if: {$gt: [r.price, '$stats.price']},
then: r.one,
else: '$stats.one'
}
},
'stats.openDate': {
$cond: {
if: {$gt: [r.price, '$stats.price']},
then: new Date(),
else: '$stats.openDate'
}
}
}
}], (err, data) => console.log(data)
)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question