OPTIONS

$push

$push

The $push operator appends a specified value to an array.

db.collection.update( <query>,
                      { $push: { <field>: <value> } }
                   )

The following example appends 89 to the scores array for the first document where the name field equals joe:

db.students.update(
                    { name: "joe" },
                    { $push: { scores: 89 } }
                  )

Note

  • If the field is absent in the document to update, $push adds the array field with the value as its element.

  • If the field is not an array, the operation will fail.

  • If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use $push with the $each modifier.

    The following example appends each element of [ 90, 92, 85 ] to the scores array for the document where the name field equals joe:

    db.students.update(
                        { name: "joe" },
                        { $push: { scores: { $each: [ 90, 92, 85 ] } } }
                      )
    

    Changed in version 2.4: MongoDB adds support for the $each modifier to the $push operator. Before 2.4, use $pushAll for similar functionality.

Changed in version 2.4: You can use the $push operator with the following modifiers:

  • $each appends multiple values to the array field,
  • $slice, which is only available with $each, limits the number of array elements, and
  • $sort, which is only available when used with both $each and $slice, orders elements of the array. $sort can only order array elements that are documents.

When used in conjunction with the other modifiers, the $each modifier must be the first modifier.

The following example uses:

  • the $each modifier to append documents to the quizzes array,
  • the $sort modifier to sort all the elements of the modified quizzes array by the ascending score field, and
  • the $slice modifier to keep only the last five sorted elements of the quizzes array.
db.students.update( { name: "joe" },
                    { $push: { quizzes: { $each: [ { id: 3, score: 8 },
                                                   { id: 4, score: 7 },
                                                   { id: 5, score: 6 } ],
                                          $sort: { score: 1 },
                                          $slice: -5
                                        }
                             }
                    }
                  )
←   $pushAll $each  →
ON THIS PAGE