0

I have a dataset like this:

{
    "_id" : ObjectId("5a7bee68996b551034015a15"),
    "sequenceid" : 1,
    "fruit" : [ 
        {
            "name" : "@APPLE",
            "value" : 2
        }, 
        {
            "name" : "@BANANA",
            "value" : 1
        }, 
        {
            "name" : "@ORANGE",
            "value" : 5
        }
}

want to update only Apple value i.e from 2 to 25. Expected result will be:

{
    "_id" : ObjectId("5a7bee68996b551034015a15"),
    "sequenceid" : 1,
    "fruit" : [ 
        {
            "name" : "@APPLE",
            "value" : 25
        }, 
        {
            "name" : "@BANANA",
            "value" : 1
        }, 
        {
            "name" : "@ORANGE",
            "value" : 5
        }
}

I tried the code but this will replace all entry and do only one entry. My code is

db.Collection.update({'sequenceid': 1}, {$set: {'fruit' : {'name': '@APPLE', 'value': parseFloat(25)}}}, function(error, result){
  if(error){
console.log('error');
} else {
 console.log('success');
}
});

It can produce the result:

{
    "_id" : ObjectId("5a7bee68996b551034015a15"),
    "sequenceid" : 1,
    "fruit" : [ 
        {
            "name" : "@APPLE",
            "value" : 25
        }
}//Delete all my rest entry

How I can Do this. I am a newbie on MongoDB

Ankit
  • 951
  • 1
  • 9
  • 29

3 Answers3

2

This will update only the first occurrence of record.For reference MongoDB - Update objects in a document's array (nested updating)

db.collection.update({ _id: ObjectId("5a7bf5586262dc7b9f3a8422") ,"fruit.name" : "@APPLE"},
   { $set:
      {
       "fruit.$.value" : 25

      }
   })
Anusha kurra
  • 482
  • 3
  • 9
1

If you are writing JavaScript query then you can update like this

 db.collection.find({'sequenceid': 1}).forEach(function(x){
        x.fruit.forEach(function(y){
                if(y.name=="@APPLE")
                {
                    y.value = 25 
                }
            })
        db.collection.update({_id:x._id},x)
    })
Murugan Perumal
  • 975
  • 5
  • 15
0
db.Collection.update({
            _id: ObjectId("5a7bee68996b551034015a15"),
            "fruit": {
                $elemMatch: {
                    "name": "@APPLE"
                }
            }
        }, {
            $set: {
                "fruit.$.value": 25

            }
        })

In above update operation $elemMatch operator is used to search a value in an array and in $set stage positional operator $ is used to update value of specific key belonging to an array element

Rubin Porwal
  • 3,736
  • 1
  • 23
  • 26