MongoDB concatenate strings from two fields into a third field

Yogesh Mangaj picture Yogesh Mangaj · Oct 10, 2012 · Viewed 26k times · Source

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.

Answer

rebe100x picture rebe100x · Jan 21, 2016

You can use aggregation operators $project and $concat:

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