Perform an update on Mongo DB grouped fields

Asked

Viewed 24 times

0

I have a Node application that connects to Mongodb, in it I have an endpoint using express that returns me the largest balances grouped by agency:

router.get("/private", async (_, res) => {
  try {
    const accounts = await accountsModel.aggregate([
      {
        $group: {
          _id: "$agencia",
          maxBalance: { $max: "$balance" },
        },
      },
    ]);
    res.send(accounts);
  } catch (error) {
    res.status(500).send(error);
  }
});

This endpoint returns me the following result:

inserir a descrição da imagem aqui

Only I need to update the agency values (_id) all to 99. Does anyone know how to do this on Mongodb?

1 answer

0

I did as follows, I do not know if it is ideal or if it is possible to update with grouping in the same method:

router.get("/private", async (_, res) => {
  try {
    const accounts = await accountsModel.aggregate([
      {
        $group: {
          _id: "$agencia",
          maxBalance: { $max: "$balance" },
        },
      },
    ]);
    accounts.forEach(async (ag) => {
      await accountsModel.updateMany(
        { balance: ag.maxBalance },
        { $set: { agencia: 99 } },
        { new: true }
      );
    });
    const private = await accountsModel.find({ agencia: 99 });
    res.send(private);
  } catch (error) {
    res.status(500).send(error);
  }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.