notElonMusk
notElonMusk

Reputation: 374

Update two nested elements in Mongo

I'm having trouble figuring out how to increment the 'totalVisits' and the 'number' of the visit matching by "Date". Trying to track my own visiting. I have lodash and moment at my disposal. Any ideas?

  campaigns: {
    type: [
      {
        _id: {
          type: ObjectId,
        },
        totalVisits: {
          type: Number,
        },
        visits: {
          type: [
            {
              date: {
                type: String,
              },
              number: {
                type: Number,
              },
            },
          ],
        },
etc....

So far I can update the total using this:

    await Views.findOneAndUpdate(
          { "campaigns._id": "{ID}" },
          {
            $inc: { "campaigns.$.totalSignups": 1 },
          }
        );

Upvotes: 0

Views: 31

Answers (1)

Dheemanth Bhat
Dheemanth Bhat

Reputation: 4452

Try this:

db.campaigns.findOneAndUpdate(
    {
        "campaigns._id": ObjectId("6041d121c1fc9029c4596778")
    },
    {
        $inc: {
            "campaigns.$.totalVisits": 1,
            "campaigns.$.visits.$[].number": 1
        }
    },
    {
        returnNewDocument: true
    }
);

Upvotes: 1

Related Questions