1

my array is as following:

{
    "_id" : ObjectId("5704cf4da64ffd34d7285fef"),
    "names" : [ 
        {
            "name" : "harjeet"
        }, 
        {
            "name" : "harjeet123"
        }, 
        {
            "name" : "harjeet1234"
        }
    ]
}

i need to update name as "harjeet12345", all of them.

my research found about this: https://jira.mongodb.org/browse/SERVER-1243

Is there any way to perform this update

Community
  • 1
  • 1
Harjeet Jadeja
  • 1,594
  • 4
  • 19
  • 39
  • do u want to set to "harjeet12345" every "name" array element of "names" field of every document in the collection? – zeugor Apr 06 '16 at 10:24

2 Answers2

1
var nameStr = "harjeet12345";
c.find().forEach(function (doc) {
    var newNameArray = [];
    doc.names.forEach(function (y) {
        var newName = {name : "zeugor"}
        newNameArray.push(newName);
    });

    c.update(
        { _id: doc._id},
        {"$set" : {"names" : newNameArray}}
    )    
})
zeugor
  • 822
  • 1
  • 8
  • 18
0

Well as you know this is an issue with mongodb embedded documents and array of documents. Since mongodb MongoDB jira have approved its modification but that is still pending and hope to see in next release. here is something you can use for now

db.yourcollection.find({}).forEach(function(tmp){
    names = [];
    tmp.names.forEach(function(name){
        names.push({name : 'rummykhan'})
    });
    tmp.names = names;
    db.yourcollection.save(tmp)
})
rummykhan
  • 2,603
  • 3
  • 18
  • 35