Articles → MONGODB → $Push, $Pull, And $Pop Operators In Mongodb

$Push, $Pull, And $Pop Operators In Mongodb






Sample Collection




Picture showing the sample document collection in mongodb



$Push Operator




db.mycollection.updateOne(
    { name: "Jane Smith" },
    { $push: { hobbies: "Running" } }
)




Picture showing executing the $push operator in mongodb




Picture showing the output of $push operator in mongodb



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' ] } } }
)


Picture showing inserting multiple values in an array using the $push and $each operators




Picture showing multiple values inserted in an array using the $push and $each operators



$Pull Operator




db.mycollection.updateOne(
    { name: "Jane Smith" },
    { $pull: { hobbies: "Running" } }
)


Picture showing the output of $pull operator in mongodb



$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 } }
)


Picture showing removing the element from an array using the $pop operator




Picture showing the output of $pop operator in mongodb



Posted By  -  Karan Gupta
 
Posted On  -  Thursday, March 28, 2024
 
Updated On  -  Wednesday, April 3, 2024

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250