0
db.collection.updateOne({
    someId: "myId",
},
{
    $set: {
        startDate: {
            $subtract: ["$startDate", 18000000] // this is 5 hours in ms
        },
        endDate: {
            $add: ["$endDate", 18000000]
        }
    }
})

Above is the current code I have, with a few name changes. I want to know how I can update the doc's startDate and endDate fields with subtraction and addition, but when I run this I don't get any changes.

I have checked the documentation, and I can't use $dateAdd because I'm on 4.4.12 and that requires 5.0; also in the updateOne documentation I don't see any examples with addition or subtraction.

I've also gotten the error: The dollar ($) prefixed field '$add' in 'endDate.$add' is not valid for storage. when trying to do it this way. I tried using $update even though that's deprecated, but that obviously didn't work.

Does anyone see any glaring issues, or have a recommendation of how to solve this?

AliveSquare
  • 27
  • 1
  • 7
  • you are using pipeline operators, without pipeline update, you can make the update a pipeline update by adding [] like `[{$set ..........}]` and i think you will be ok, if not give if you can sample data also – Takis Mar 08 '22 at 17:33
  • @Takis_ thank you! I didn't know updateOne operated like an aggregate, I thought it was structured like a find. I added the [] around the operation and that seemed to work. – AliveSquare Mar 08 '22 at 17:48
  • @Takis go ahead and copy your comment into the answer; it *is* the answer. – Buzz Moschetti Mar 08 '22 at 18:43

1 Answers1

2

Query

  • when we use aggregate operators for the update, we have to use a pipeline update
  • to make it a pipeline update here we only need to surround with [] like
    [{$set ..........}]
  • we can't mix aggregate operators with update operators, we use either the one or the other, and when we use pipeline update we put the stages into []
  • pipeline updates need MongoDB >= 4.2
db.collection.update({
    someId: "myId",
},
[{
    $set: {
        startDate: {
            $subtract: ["$startDate", 18000000] // this is 5 hours in ms
        },
        endDate: {
            $add: ["$endDate", 18000000]
        }
    }
}],
{"multi" : false})
Takis
  • 8,314
  • 2
  • 14
  • 25