Updating data

To update a record, use the update() function, but include a find query as the first parameter:

> db.newCollection.update({ name: 'Jason Krol' }, { website: 
'http://jasonkrol.com' })

There's a bit of a catch here. If you perform a new find({ name: 'Jason Krol' }) operation, something strange happens. No data is returned. What happened? Well, the second parameter in the update() function is actually the new version of the complete document. Since, you only wanted to update the website field, what actually happened was that the document that was found was replaced with the new version that consists of only the website field. To reiterate, the reason this happens at all is because with NoSQL such as MongoDB, the document does not have a set number of fields (as a relational database does). To fix this problem, you should use the $set operator instead:

> db.newCollection.update({ name: 'Jason Krol' }, { $set: { website: 
'http://jasonkrol.com'} })

There may be a time when you want to update a document, but the document itself may or may not exist. What happens when the document does not exist, and you'd like a new one to be created instantly based on the updated values you provide? Well, there's a handy function just for that. Pass {upsert: true} as the third parameter to the update() function:

> db.newCollection.update({ name: 'Joe Smith' }, { name: 'Joe Smith', 
website: 'http://google.com' }, { upsert: true })

If we have a document with a name field that matches Joe Smith, the website
field will be updated (and the name field preserved). However, if we do not have
a matching document, a new one will be created automatically.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.244.250