0

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 },
          }
        );
notElonMusk
  • 314
  • 1
  • 4
  • 21

1 Answers1

1

Try this:

db.campaigns.findOneAndUpdate(
    {
        "campaigns._id": ObjectId("6041d121c1fc9029c4596778")
    },
    {
        $inc: {
            "campaigns.$.totalVisits": 1,
            "campaigns.$.visits.$[].number": 1
        }
    },
    {
        returnNewDocument: true
    }
);
Dheemanth Bhat
  • 4,269
  • 2
  • 21
  • 40
  • Nice @DheemanthBhat ! How is it working? And can it be adapted to push based on Date. In this scenario I'm trying to push visits by date. If the date doesn't exist it can push another 'visit' item, if it does, update the number for that day – notElonMusk Mar 05 '21 at 23:49
  • No u cannot do both in same query. Check this: https://stackoverflow.com/questions/39781173/update-nested-object-in-mongodb-if-it-exists-otherwise-add-it or https://stackoverflow.com/questions/41888312/update-element-in-array-if-exists-else-insert-new-element-in-that-array-in-mongo – Dheemanth Bhat Mar 06 '21 at 10:09