Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB concatenate strings from two fields into a third field

Tags:

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 } },   { $set: { column_2: { $add: ['$column_4', '$column_3'] } } },   false, true ) 

which doesn't seem to work though, and throws not ok for storage.

I've also tried this:

db.collection.update(   { "_id": { $exists : true } },   { $set: { column_2: { $add: ['a', 'b'] } } },   false, true ) 

but even this shows the same error not ok for storage.

I want to concatenate only on the mongo server and not in my application.

like image 596
Yogesh Mangaj Avatar asked Oct 10 '12 13:10

Yogesh Mangaj


2 Answers

You can use aggregation operators $project and $concat:

db.collection.aggregate([   { $project: { newfield: { $concat: [ "$field1", " - ", "$field2" ] } } } ]) 
like image 139
rebe100x Avatar answered Oct 21 '22 05:10

rebe100x


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.

like image 37
William Z Avatar answered Oct 21 '22 04:10

William Z