Articles → MONGODB → $Push, $Pull, And $Pop Operators In Mongodb
$Push, $Pull, And $Pop Operators In Mongodb
Sample Collection
$Push Operator
db.mycollection.updateOne(
{ name: "Jane Smith" },
{ $push: { hobbies: "Running" } }
)
Pushing Multiple Values In An Array
db.collection.updateOne(
{ _id: ObjectId("document_id") }, // Match condition to identify the document
{ $push: { arrayField: { $each: [ value1, value2, ... ] } } }
)
db.mycollection.updateOne(
{ _id: ObjectId("6597b8a02695219f3c55e481") },
{ $push: { hobbies: { $each: [ 'Cycling', 'Painting' ] } } }
)
$Pull Operator
db.mycollection.updateOne(
{ name: "Jane Smith" },
{ $pull: { hobbies: "Running" } }
)
$Pop Operator
{ $pop: { <field>: 1 } }: Removes the last element of the array.
{ $pop: { <field>: -1 } }: Removes the first element of the array.
db.mycollection.updateOne(
{ name: 'John Doe' },
{ $pop: { hobbies: 1 } }
)