S
S
Sworry2015-11-12 16:42:00
JavaScript
Sworry, 2015-11-12 16:42:00

How to update field value in mongo?

This is how the db schema looks like:

{"_id":"563f480fb5c2187503eefc1a","ownerBy":"56335521f2f4a3150349d78d","data":{"username1":"76561198060520554","username2":"76561198060520554","username3":"76561198060520554","username4":"76561198060520554","username5":"76561198060520554"},"__v":0}

An object of the form comes from the client:
{ newValue: 'as76561198060520554',
  id: 'username1',
  column: 'selectable' }

How to find the field(id) and replace the value with newValue?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sveratum, 2015-11-13
@srsd

Something like this:
db.collection.find({ "data.username1" : {$exists: true}}).forEach( function(myDoc) { db.collection.update({_id: myDoc._id}, {$set : {"data.username1": myDoc.newValue}} )});
If I correctly understood the intricacies of your data.

L
lega, 2015-11-13
@lega

db.collection.update({ 'data.username1': {$exists: true} }, { $set: { 'data.username1': newValue }}, true)

Such a request should update all documents where this field is present, but since a query without an index (and not making an adequate one for this data), then it will enumerate all the documents - this is slow and will slow down on a large collection.
Therefore, it is better to make "auxiliary data" for the array - duplicate the identifiers in the array:
{
  "_id":"563f480fb5c2187503eefc1a"
  "ownerBy":"56335521f2f4a3150349d78d",
  "data":{"username1":"76561198060520554","username2":"76561198060520554"...},
  "__v":0,
  userList: ['username1', 'username2', 'username3']
}

And make an index: db.collection.ensureIndex({userList: 1})
This userList can be updated in the same command as the data using $addToSet (and $pull to remove from the list).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question