Home > Net >  How do I use $pop in mongoDB more than ones, NodeJs
How do I use $pop in mongoDB more than ones, NodeJs

Time:11-05

I have to delete the last 8 elements of an array saved in my mongodb database. With $pop I managed to delete the last, but not 8. How can I do that?

  PostSchema.updateOne(
    { email: data.email },
    {
      $pop: {
        gratitudeLog: 1,
      },
    },
    (err, user) => {
      if (err) {
        res.sendStatus(404);
      } else {
        res.status(200).json(user);
      }
    }
  );

I would appreciate some help.

Thanks

CodePudding user response:

Use $slice to remove the last 8 elements. Remember to check whether the array size is greater than 8.

db.collection.update({
  email: "[email protected]"
},
[
  {
    $set: {
      gratitudeLog: {
        "$cond": {
          "if": {
            $gt: [
              {
                $size: "$gratitudeLog"
              },
              8
            ]
          },
          "then": {
            "$slice": [
              "$gratitudeLog",
              {
                "$subtract": [
                  {
                    "$size": "$gratitudeLog"
                  },
                  8
                ]
              }
            ]
          },
          "else": []
        }
      }
    }
  }
],
{
  multi: true
})

Mongo Playground

  • Related