Home > Net >  mongodb push field in update aggration pipe
mongodb push field in update aggration pipe

Time:12-28

I have the following mongo document (very simple):

[
  {
    "_id": ObjectId("609c2c2d420a73728827e87f"),
    "timestamp": "2021-01-01 12:00:00",
    userId: 1,
    "users": []
  }
]

What I want to achieve is the following: when updating the document, I want to add (push) a username to the users array. But when the array reaches 5 usernames, I want to pop the first one out of the list and add a new one. So a max of 5 usernames should be in the list.

I'm trying to do this like this, but ofc this does not work. Here is my query (with an aggregation pipeline) so far:

db.collection.update({
  "userId": 1
},
[
  {
    $set: {
      timestamp: "2021-01-01 14:00:00"
    }
  },
  {
    $cond: {
      if: {
        "users.4": {
          $exists: true
        }
      },
      then: {
        $pop: {
          users: -1
        }
      },
      else: "$users"
    }
  },
  {
    $push: {
      "users": "my_username"
    }
  }
])

I'm a beginner in mongodb and I'm using node.js mongoose.

Thanks in advance!

CodePudding user response:

Replace

{ $push: { "users": "my_username" } }

by

{ $set: { users: { $concatArrays: [ "$users", ["my_username"] ] } } } 

You are using an aggregation pipeline but $push is an Update Operator

For the same reason use use $slice instead of $pop

  • Related