increment document field depending on array length

Viewed 31

The reason behind that is:

Whenever somebody fetches the blog post via an api his IP adress gets added to ips via $addToSet.

In the background i have an cronjob that needs to count the array, increment the views counter and clean the array.

return Blog.updateMany({}, {
  $inc: {
    views: {
      $size: "$ips"
    }
  }
}).exec()

I try to update an field. The field views is numeric and ips is an array.

What i want to do is to increment views depending on the array and after that i want to clear the array.

But this fails. Has somebody an solution?

1 Answers

You can try update with aggregation pipeline,

  • $size to get total size of array in number, $add to sum the old and new value, and clean ips array
return Blog.updateMany({}, 
  [{
    $set: {
      views: { $add: ["$views", { $size: "$ips" }] },
      ips: []
    }
  }]
).exec()

Playground

Related