updateMany() on array

Viewed 333

In my application i have a collection called Blog and i run this query every 24h

  await Blog.updateMany({}, [
    {
      $set: {
        viewed: {
          $add: [{ $size: "$visitorIps" }, "$viewed"]
        },
        visitorIps: []
      }
    }
  ]);

My problem is that i have a second collection called Users. Inside of Users i have an array called posts and here are all posts from that user saved.

{
   _id: 234klj2ö34,
   user: "Max",
   posts: [
      {
         _id: 5dgewef323523,
         name: "My first blogpost",
         content: "...",
         viewed: 0,
         visitorIps: ["192.168.23.12"]
      }
   ]
}

Now i need the same query on my second collection for each array. How do i do it? I tried something like this but it doesnt worked:

  await User.updateMany({}, [
    {
      $set: {
        "posts.$[].viewed: {
          $add: [{ $size: "posts.$[].visitorIps" }, "posts.$[].viewed"]
        },
        "posts.$[].visitorIps": []
      }
    }
  ]);

But thats completely wrong. Could somebody help me here out?

1 Answers

You can try using $map,

  • your logic and code remain same for viewed and visitorIps
  • $mergeObjects will merge current cursor fields and viewed and visitorIps that we have calculated
await User.updateMany({},
    [{
        $set: {
            posts: {
                $map: {
                    input: "$posts",
                    as: "post",
                    in: {
                        $mergeObjects: [
                            "$$post",
                            {
                                "viewed": {
                                    $add: [{ $size: "$$post.visitorIps" }, "$$post.viewed"]
                                },
                                "visitorIps": []
                            }
                        ]
                    }
                }
            }
        }
    }]
)
Related