MongoDB concatenate strings from two fields into a third field

我的未来我决定 提交于 2019-11-28 23:35:50

Unfortunately, MongoDB currently does not allow you to reference the existing value of any field when performing an update(). There is an existing Jira ticket to add this functionality: see SERVER-1765 for details.

At present, you must do an initial query in order to determine the existing values, and do the string manipulation in the client. I wish I had a better answer for you.

You can use aggregate, $project and $concat : https://docs.mongodb.org/v3.0/reference/operator/aggregation/project/ https://docs.mongodb.org/manual/reference/operator/aggregation/concat/

It would be something like this :

db.collection.aggregate(
   [
      { $project: { newfield: { $concat: [ "$field1", " - ", "$field2" ] } } }
   ]
)
Nizam Khan

let suppose that you have a collection name is "myData" where you have data like this

{
"_id":"xvradt5gtg",
"first_name":"nizam",
"last_name":"khan",
"address":"H-148, Near Hero Show Room, Shahjahanpur",
}

and you want concatenate fields (first_name+ last_name +address) and save it into "address" field like this

{
"_id":"xvradt5gtg",
"first_name":"nizam",
"last_name":"khan",
"address":"nizam khan,H-148, Near Hero Show Room, Shahjahanpur",
}

now write query will be

{
var x=db.myData.find({_id:"xvradt5gtg"});
x.forEach(function(d)
    { 
        var first_name=d.first_name;
        var last_name=d.last_name;
        var _add=d.address;  
        var fullAddress=first_name+","+last_name+","+_add; 
        //you can print also
        print(fullAddress); 
        //update 
        db.myData.update({_id:d._id},{$set:{address:fullAddress}});
    })
}

You can also follow the below.

db.collectionName.find({}).forEach(function(row) { 
    row.newField = row.field1 +"-" +row.field2
    db.collection.save(row);
});
db.myDB.find().forEach(function(e){db.myDB.update({"_id":e._id},{$set{"name":'More' + e.name + ' '}});

This is a solution!!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!