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.
You can use aggregation operators $project
and $concat
:
db.collection.aggregate([ { $project: { newfield: { $concat: [ "$field1", " - ", "$field2" ] } } } ])
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With