Skip to content

Instantly share code, notes, and snippets.

@vhbui02
Last active May 17, 2023 08:06
Show Gist options
  • Save vhbui02/5c27fae4967f5399edda9e7da5540b02 to your computer and use it in GitHub Desktop.
Save vhbui02/5c27fae4967f5399edda9e7da5540b02 to your computer and use it in GitHub Desktop.
[MongoDB U operation] #mongodb

Update Method

updateOne()
updateMany()
replaceOne() // replace at most, 1 single document that match specified filter, regardless of other matched documents
// replace diff from update, that it overrides the whole document, not just 1 or 2 field.

findAndModify()
findOneAndUpdate()
findOneAndReplace()
bulkWrite()

Updates with Aggregation Pipeline

updateOne(
  {
    _id: 3,
  },
  // aggregation pipeline,
  // it is an array
  [
    {
      $set: {
        test3: 98,
        // aggregation variable, can only be used inside aggregation stage.
        modified: '$$NOW',
      },
    },
  ]
)

db.students2.insertMany([
   {
      '_id': 1,
      quiz1: 8,
      // missing test 1
      test2: 100,
      quiz2: 9,
      modified: new Date('01/05/2020'),
   },
   {
      '_id': 2,
      // missing quiz 1
      quiz2: 5,
      test1: 80,
      test2: 89,
      modified: new Date('01/05/2020'),
   },
])

db.students2.updateMany(
   {
      // empty => update all
   },
   [
      {
         // standardize the fields across documents (e.g. document in the collection should have the same fields value and existence)
         $replaceRoot: {
            newRoot: {
               // set default value to 0
               $mergeObjects: [
                  { quiz1: 0, quiz2: 0, test1: 0, test2: 0 },
                  '$$ROOT', // refers to the current Document being modified

                  // => the current document field will override the default one
               ],
            },
         },
      },
      {
         $set: {
            modified: '$$NOW',
         },
      },
   ]
)

db.students2.find({})

db.students4.insertMany([
   { '_id': 1, 'quizzes': [4, 6, 7] },
   { '_id': 2, 'quizzes': [5] },
   { '_id': 3, 'quizzes': [10, 10, 10] },
])

db.students4.updateOne(
   {
      _id: 2,
   },
   [
      {
         $set: {
            quizzes: {
               // aggregation pipeline operator
               $concatArrays: ['$quizzes', [8, 6]],
            },
         },
      },
   ]
)

db.students4.find({})

db.temperatures.insertMany([
   { '_id': 1, 'date': ISODate('2019-06-23'), 'tempsC': [4, 12, 17] },
   { '_id': 2, 'date': ISODate('2019-07-07'), 'tempsC': [14, 24, 11] },
   { '_id': 3, 'date': ISODate('2019-10-30'), 'tempsC': [18, 6, 8] },
])

db.temperatures.find({})

db.temperatures.updateMany(
   {
      // empty
   },
   [
      {
         // aggregation stage
         $addFields: {
            // new field's about to be added
            'tempsF': {
               // use existed data to produce new data for new field
               // map each array element of 'tempsC'
               $map: {
                  input: '$tempsC',
                  as: 'celsius',
                  in: {
                     // agg pipeline operator
                     $add: [
                        {
                           // agg pipeline operator
                           $multiply: ['$$celsius', 9 / 5],
                        },
                        32,
                     ],
                  },
               },
            },
         },
      },
   ]
)

Update using Update Operators

updateOne(
  {
		// empty	
    // or
    _id: 100,
    'custom field': 'abcxyz'
	}, 
  {
    
		$inc: {
    	'some field': 1 // increase by 1
      'some sub document name.field': -2 // decrease by 2
    }, 
    $currentDate: {
  		'some field with time data type': true
      
      // could use dot notation here, remember to put it inside double quote
      // or 
      // 'some field with time data type' : {
      // 		$type: "date"
      // 		// $type: "timestamp"
      // }
  	},
    $unset: {
      'some field that want to remove': "" // empty string
      'some field that want to remve 2': "" // empty string
    }, 
    // the most common update operator
    $set: {
  		'some int field': 100,
      'some sub-document field': {'nested field 1': 'abc', 'nested field 2': 9999}
      'some array field': [100, 200, 300]
    	// could use dot notation here
  	}, 
  }
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment