[SERVER-19974] Add $unshift modifier as alias to $push $each $position: 0 Created: 15/Aug/15  Updated: 06/Dec/22

Status: Backlog
Project: Core Server
Component/s: Write Ops
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Minor - P4
Reporter: Dan Dascalescu Assignee: Backlog - Query Optimization
Resolution: Unresolved Votes: 5
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Assigned Teams:
Query Optimization
Participants:

 Description   

Re-filing this as an individual request from SERVER-2362, focusing only on $unshift.

I would like to see $unshift implemented simply as an alias to $push with $position: 0, but without requiring $each, because it doesn't read super intuitively:

Before:

$push: {
    scores: {
        $each: [ 50, 60, 70 ],
        $position: 0
    }
}

After:

$unshift: {
    scores: [ 50, 60, 70 ]
}

Much cleaner.

Use cases

There are at least four questions on StackOverflow asking how to insert elements at the beginning of an array:

  1. http://stackoverflow.com/questions/7936019/how-do-i-add-a-value-to-the-top-of-an-array-in-mongodb
  2. http://stackoverflow.com/questions/13649010/add-values-to-the-beginning-of-an-array-with-mongodb
  3. http://stackoverflow.com/questions/10094573/use-mongodb-array-as-stack
  4. http://stackoverflow.com/questions/10131957/can-you-have-mongo-push-prepend-instead-of-append


 Comments   
Comment by Asya Kamsky [ 29/Jun/19 ]

With 4.2 adding updates with aggregation pipeline syntax it is now possible to express this with

[ {$set:{ comments: {$concatArrays:  [  { newCommentDoc} ], "$comments" ] } } } ]

Comment by Dan Dascalescu [ 15/Aug/15 ]

The scores example is from the $position docs, but here's an example that reads even less intuitively:

$push: {
    comments: {
        $each: {
          by: "Joe",
          text: "Some comment"
        },
        $position: 0
    }
}

Generated at Thu Feb 08 03:52:44 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.