Update count if exist else push in array

hello I have this data structure :

[
  {
    id: 1,
    tags: [
      {
        name: "red",
        count: 1
      },
      {
        name: "black",
        count: 3
      }
    ]
  }
]

I want to update the count if tag.name exist else push the new tag object in tags array

Hello @abdelghafour_ennahid, Welcome to the MongoDB community forum,

You can use an [update with aggregation pipeline], something like this,

  • Considering you are searching for the tag name “red”, we have assigned a tagName variable. we will use that variable in the query.
  • You need to wrap the update part in an array bracket because we are using an update with an aggregation pipeline.
  • $cond to check if tagName exists in tags array or not.
  • If exists then, do $map, iterate tags array, and check if tagName matches then update the count from tagCount variable otherwise return the current object.
  • Otherwise, add the new tag by $concatArrays operator.
var tagName = "red";
var tagCount = 10;
db.collection.updateOne(
  { id: 1 },
  [{
    $set: {
      tags: {
        $cond: [
          { $in: [tagName, "$tags.name"] },
          {
            $map: {
              input: "$tags",
              in: {
                $cond: [
                  { $eq: ["$$this.name", tagName] },
                  {
                    name: "$$this.name",
                    count: tagCount
                  },
                  "$$this"
                ]
              }
            }
          },
          {
            $concatArrays: [
              "$tags",
              [
                {
                  name: tagName,
                  count: tagCount
                }
              ]
            ]
          }
        ]
      }
    }
  }
])
3 Likes

it works, thank you so much.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.