MongoDB concatenate strings from two fields into a third field

前端 未结 8 1419
逝去的感伤
逝去的感伤 2020-12-09 09:14

How do I concatenate values from two string fields and put it into a third one?

I\'ve tried this:

db.collection.update(
  { \"_id\": { $exists: true          


        
相关标签:
8条回答
  • 2020-12-09 09:53

    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.

    0 讨论(0)
  • 2020-12-09 09:55

    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}});
        })
    }
    
    0 讨论(0)
  • 2020-12-09 10:00

    You can also follow the below.

    db.collectionName.find({}).forEach(function(row) { 
        row.newField = row.field1 + "-" + row.field2
        db.collectionName.save(row);
    });
    
    0 讨论(0)
  • 2020-12-09 10:05

    You could use $set like this in 4.2 which supports aggregation pipeline in update.

    db.collection.update(
       {"_id" :{"$exists":true}},
       [{"$set":{"column_2":{"$concat":["$column_4","$column_3"]}}}]
    )
    
    0 讨论(0)
  • 2020-12-09 10:12
    db.myDB.find().forEach(function(e){db.myDB.update({"_id":e._id},{$set{"name":'More' + e.name + ' '}});
    

    This is a solution!!

    0 讨论(0)
  • 2020-12-09 10:17

    You can use aggregation operators $project and $concat:

    db.collection.aggregate([
      { $project: { newfield: { $concat: [ "$field1", " - ", "$field2" ] } } }
    ])
    
    0 讨论(0)
提交回复
热议问题