2

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?

0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.