Blog

MongoDB Array Operators
Posted on July 17, 2015 in MongoDB by Matt Jennings

Example Using $push and $each to Insert a New Field (AKA JavaScript Object), that has an Array Value with Multiple Elements, into a Document

db.schools.update( {name: "San Jose"}, {$push: {amenities:{$each: ["onsite dorm", "cafeteria", "pool"] } } } )

Example Using $push to Update a Document to Insert a New Field that Contains ONE Array Element OR if Said Field Name Doesn’t Exist Insert It

db.schools.update( {name: "San Jose"}, {$push: {amenities: "hot tub" } } )

Use {$pop: {amenities: -1 } to Remove the First Field Array Element

db.schools.update( {name: "San Jose"}, {$pop: {amenities: -1 } } )

Use {$pop: {amenities: 1 } to Remove the Last Field Array Element

db.schools.update( {name: "San Jose"}, {$pop: {amenities: 1 } } )

Use {$addToSet: {amenities: "table tennis" } } to Add an Array Element to a Field ONLY if it Doesn’t Exist

db.schools.update( {name: "San Jose"}, {$addToSet: {amenities: "table tennis" } } )

Use {$pull: {amenities: "pool" } } to Remove a Matched Element from a Field’s Array Value

db.schools.update( {name: "San Jose"}, {$pull: {amenities: "pool" } } )

Leave a Reply

To Top ↑