Home > Net >  MongoDB Node: Positional Operator In Combination With Conditional & Equals Operator
MongoDB Node: Positional Operator In Combination With Conditional & Equals Operator

Time:01-27

I have the following document structure:

{
  name: "JohnDoe",
  list: [
    { text: "Text", checked: "2023-01-23" },
    // ...
  ],
}

Given a name and text I can find one document and then update the checked field of the correct array element:

collection.updateOne(
  { name, "list.text": text },
  { $set: { "list.$.checked": "2023-01-24" }}
);

Now my question is: Is it possible to calculate the new value based on the current value using the $cond and $eq operators, and if so, what would be the correct syntax? Specifically, I want to differentiate between the case in which the value is the current date, and the case where it is not.

From my understanding, I have to use an aggregation pipeline in order for this to work. So I tried the following:

collection.updateOne(
  { name, "list.text": text },
  [
    {
      $set: {
        "list.$.checked": {
          $cond: {
            if: { $eq: ["list.$.checked", date()] },
            then: "",
            else: date(),
          },
        },
      },
    },
  ],
);

However, this gets me the error message "Invalid $set :: caused by :: FieldPath field names may not start with '$'. Consider using $getField or $setField.". I don't understand how this query is supposed to look like for it to work.

CodePudding user response:

$cond and $eq are aggregation operators, not update operators.
In order to use those operators in an update, you will need to use the pipeline type of update.
However, inside the pipeline you will not be able to use the $ positional operator, so you would likely need to $map the array to set that value.

  • Related