Open In App

MongoDB – $position Modifier

MongoDB provides different types of array update operators to update the values of the array fields in the documents and $position modifier is one of them. This modifier is used to specify the location in the array at which the $push operator inserts items. Without $position modifier $push operator insert items at the end of the array.

Syntax:



{
  $push: {
     <field>: {
       $each: [ <value1>, <value2>, ... ],
       $position: <number>
     }
  }
}

Here, <number> indicates the position of the item in the array according to the zero-based index.

In the following examples, we are working with:



Database: GeeksforGeeks
Collection: contributor
Document: two documents that contain the details of the contributor in the form of field-value pairs.

Adding items at the start of the array:

In this example, we are adding items, i.e., [“C#”, “Perl”] in the beginning(i.e., position 0 )of the language field.




db.contributor.update({name: "Rohit"}, 
                      {$push: { language: { $each: ["C#", "Perl"],
                        $position: 0}}})

Adding items to the middle of the array:

In this example, we are adding items, i.e., [“Perl”] in the middle(i.e., position 2 )of the language field.




db.contributor.update({name: "Suman"}, 
                      {$push: { language: { $each: [ "Perl"], 
                        $position: 2}}})

Using a negative index to add items to the array:

In this example, we are adding items, i.e., [“C”] just before the last item in the language field.




db.contributor.update({name: "Rohit"},
                      {$push: { language: { $each: [ "C"], 
                        $position: -1}}})


Article Tags :