Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to update a single field in a MongoDB collection for all documents matching a specific criteria
// FROM: http://www.mongodb.org/display/DOCS/Updating#Updating-update%28%29
//
// db.collection.update( criteria, objNew, upsert, multi )
// criteria - query which selects the record to update;
// objNew - updated object or $ operators (e.g., $inc) which manipulate the object
// upsert - if this should be an "upsert"; that is, if the record does not exist, insert it
// multi - if all documents matching criteria should be updated
//
// SQL VERSION:
// UPDATE myTable SET dateField = '2011-01-01' WHERE condField = 'condValue'
db.myCollection.update({condField: 'condValue'}, { $set: { dateField: new Date(2011, 0, 1)}}, false, true);
@o-nix

This comment has been minimized.

Copy link

@o-nix o-nix commented Mar 19, 2012

Yay. Thank you. :)

@PandaWhisperer

This comment has been minimized.

Copy link

@PandaWhisperer PandaWhisperer commented Jun 27, 2014

Works! The 4th parameter was what I was missing.

@sanat51289

This comment has been minimized.

Copy link

@sanat51289 sanat51289 commented Mar 21, 2015

The following query doesn't work, when I want to update subfield (which is an int) of one of the parent fields of all documents in a collection:

db.myCollection.update( {}, { $set: { 'rootField.toBeModifiedField': 1}}, false, true);

what am i missing?

Thanks!

@S0c5

This comment has been minimized.

Copy link

@S0c5 S0c5 commented Apr 24, 2015

brother try it:

db.myCollection.update( {}, { $set: { rootFieldto:{BeModifiedField: 1}}}, false, true);
@samelliott89

This comment has been minimized.

Copy link

@samelliott89 samelliott89 commented Sep 28, 2016

Does anyone know if it's possible to update multiple fields in the one query? I.e

return this.update({"Name": {$regex: regex}}, 
    { $set: { 'keyToUpdate': param1 , 'otherKeyToUpdate': param2 } }, {multi: true})
    .execAsync();
@iozozturk

This comment has been minimized.

Copy link

@iozozturk iozozturk commented Nov 8, 2016

Thank you, works!

@fadeaway1992

This comment has been minimized.

Copy link

@fadeaway1992 fadeaway1992 commented Sep 26, 2018

Thank you!

@mfdebian

This comment has been minimized.

Copy link

@mfdebian mfdebian commented Oct 5, 2018

Thanks!

@fakefarm

This comment has been minimized.

Copy link

@fakefarm fakefarm commented Oct 26, 2018

Life's problems just decreased by one because of you. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment