Monk Driver for MongoDB – How to Update Existing Documents?

Want create site? Find Free WordPress Themes and plugins.

I’ve already listed the number of reasons I chose the Monk Driver for accessing MongoDB in the previous blog. In case, you have missed it, refer Monk Driver for MongoDB – How to Create Documents where you will also learn how to create documents. Also check, how to select documents in MongoDB with Monk.

In this blog, I’ll talk about how to update existing documents in MongoDB with Monk.

Let’s start.

First, you need to connect to MongoDB using Monk, by firing the following lines of code.

const db = require('monk')('localhost/mydb')
const users = db.get('dbusers')
db.close()

Here are 4 ways you can update existing documents in MongoDB using Monk.

1. $addToSet: Adds a value to the array. If the value is already present, the addToSet operator will do nothing. You need to keep in mind that it will not guarantee a specific arrangement of elements in the modified set.

Using addToSet :
var collection=db.get(‘collectionName’)

Adding just the key and value to specific object

collection.update({ _id: ObjectId(“58d0c7b727b1460ea5fb9275”) }, { $addToSet: { "key":
“value” } }, function (err, doc, next) {
//do your operations
})
 
Where key can be in two forms
“key”, ”key.subobjkey

Adding new object to existing object

collection.update({ _id: ObjectId(“58d0c7b727b1460ea5fb9275”) }, { $addToSet:
objectvalue } }, function (err, doc, next) {
  //do your operations
})

Adding multiple values to the array field

collection.update(
 { _id: ObjectId(“58d0c7b727b1460ea5fb9275”) },
 { $addToSet: { testkey: { $each: [ "k1", "k2", "k3" ] } } }
)

2.  $set: Set overrides the existing data of document and sub-document based on given conditions. If the field does not exist, a new field will be added with a specified value. To create an embedded document we need to specify a dot while using $set method.

Using Set:

Updating just the key and value to specific object

db.collection(‘collectionName’).update({ _id: ObjectId(“58d0c7b727b1460ea5fb9275”) }, { $set:
{ "key": “value” } }, function (err, doc, next) {
  //do your operations
})
 
Where key can be in two forms
“key”, ”key.subobjkey

Updating whole object set

db.collection(‘collectionName’).update({ condition }, { $set: object }, function (err, doc, next) {
 //do your operations
})

Updating a particular set of the object in an array of subdocument:

db.collection(‘collectionName’).update({
"_id": “given_id”,
 "subdocument.key": “value”
    }, {
  $set: {
     "subdocument.$": objectset
    }
  }, function (err, doc, next) {
     //do your operations
})

“$” will ensure the positional update that matches the criteria rather than updating the whole subdocument.
Note: use set with care because without condition it will remove all sub-documents

3. Push: Pushes the key-value pair or whole object into the existing subdocuments. The significance of this method is that in case the specified field is not there it will add field value to the document.

Pushing a set of object with specific subdocument

db.collection(‘collectionName’).update({ _id: ObjectId(“58d0c7b727b1460ea5fb9275”) },
{ $push: { “subdocument_name”:{ "key": “value” } }}, function (err, doc, next) {
 //do your operations
})

Pushing a set of object inside a specific subdocument
Say there is a collection with following structure:

{
   name: 'myDoc',
   List:
   [
    {
        id:1
        Items:
        [
            {id:1, name:'item1'},
            {id:2, name:'item2'}
        ]
        },
    {
        id:2
        Items:
        [
           {id:1, name:'item1'},
           {id:3, name:'item3'}
        ]
   }
 ]
}

To push the element id:5, name: “item5” in the subdocument list with id=2 the query will be

collection.update( { name: 'mydoc', 'list.id': 2 }, {$push: {'list.$.items': {id: 5,
name: 'item5'}}} )

4. Pull: Pull out a specific set that matches the criteria from document or subdocument.

Using $pull :
var collection=db.get(‘collectionName’)
Pulling out from mongoDB

collection.update({_id:ObjectId(“58d0c7b727b1460ea5fb9275”)}, { $pull:
{“subdocument_name”:{condition} }}, function (err, doc, next) {
       //do your operations
})

Example: To pull out all the value greater than 5 in given set

{ _id: 1, votes: [ 3, 5, 6, 7, 7, 8 ] }
collection.update({_id:1},{$pull:{votes:{$gte:5}}}, function (err, doc, next) {
//do your operations
})

That’s all for today! We will continue updating the blog with more queries. Stay tuned.
Upcoming blog on ‘Deleting’ in MongoDB using Monk.

Did you find apk for android? You can find new Free Android Games and apps.

Tags

Related Posts

Leave A Comment