Skip to content

Instantly share code, notes, and snippets.

@ats1999
Last active May 2, 2021 11:18
Show Gist options
  • Save ats1999/a652887b7d5f66ef8cbff846b14ca912 to your computer and use it in GitHub Desktop.
Save ats1999/a652887b7d5f66ef8cbff846b14ca912 to your computer and use it in GitHub Desktop.
Quick commands for MongoDB

Let's Learn MongoDB commands

Update

Definition

db.collection.update(query, update, options)

syntax

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>, // insert new one if not already persent
     multi: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>        // Available starting in MongoDB 4.2
   }
)

update attribute

db.user.updateOne({_id:"123"},{$set:{name:"New Name"}})
// name will be created if it does not exists already

increment

db.user.updateOne({_id:"123"},{$inc:{count:5}})
// increment count attribute by 5
// count=5 will be created if it does not exists already

push into array

db.user.updateOne({_id:"123"},{$push:{tags:"react"}})
// push  "react" into tags array
// tags = ["react"] will be created if it does not exists already

remove attribute

db.user.updateOne({_id:"123"},{$unset:{name:1,tags:1}})
// remove name and tags

replace

db.user.update(
   { _id: 2 },
   {
     item: "XYZ123",
     stock: 10,
     info: { publisher: "2255", pages: 150 },
     tags: [ "baking", "cooking" ]
   }
)

// all existing attributes will be removed for user _id=2
// new document will be created if user _id=2  doee not exist already

Modify a Field Using the Values of the Other Fields in the Document Link

db.collection.update({...},[$set:{new_field:"$existing_field"}],{..});

// notice the second parameter is an array insted of object
// $ sign refers the exsiting attribute
// if $existing_field is not persent then new_field will be not created
// if new_field already exist and $existing_field is not persent then new_field will be removed

// we can also have multiple $set, $unset, etc
db.collection.update({...},[
    $set:{new_field:"$existing_field"},
    $set:{new_field1:"$new_field"} // new_field is now update by previous $set
],{..});

Array Update

data

db.students.insertMany([
   { "_id" : 1, "grades" : [ 95, 92, 90 ] },
   { "_id" : 2, "grades" : [ 98, 100, 102 ] },
   { "_id" : 3, "grades" : [ 95, 110, 100 ] }
])
db.students.update({},{$set:{"grades.$[element]":100}},{arrayFilters:[{"element":{$gte:100}}],multi:true})
// make grades[i]=100 where grades[i] >= 100
// we can also include path

{"grades.$[element].path":val}
arrayFilters:[{"element.any_path":{$gte:100}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment