In MongoDB, is it possible to update the value of a field using the value from another field? The equivalent SQL would be something like:
UPDATE Person SET Name = FirstName + ' ' + LastName
And the MongoDB pseudo-code would be:
db.person.update( {}, { $set : { name : firstName + ' ' + lastName } );
You should iterate through. For your specific case:
Here's what we came up with for copying one field to another for ~150_000 records. It took about 6 minutes, but is still significantly less resource intensive than it would have been to instantiate and iterate over the same number of ruby objects.
I tried the above solution but I found it unsuitable for large amounts of data. I then discovered the stream feature:
Apparently there is a way to do this efficiently since MongoDB 3.4, see styvane's answer.
Obsolete answer below
You cannot refer to the document itself in an update (yet). You'll need to iterate through the documents and update each document using a function. See this answer for an example, or this one for server-side
eval()
.For a database with high activity, you may run into issues where your updates affect actively changing records and for this reason I recommend using snapshot()
http://docs.mongodb.org/manual/reference/method/cursor.snapshot/
The best way to do this is to use the aggregation framework to compute our new field.
MongoDB 3.4
The most efficient solution is in MongoDB 3.4 using the
$addFields
and the$out
aggregation pipeline operators.Note that this does not update your collection but instead replace the existing collection or create a new one. Also for update operations that require "type casting" you will need client side processing, and depending on the operation, you may need to use the
find()
method instead of the.aggreate()
method.MongoDB 3.2 and 3.0
The way we do this is by
$project
ing our documents and use the$concat
string aggregation operator to return the concatenated string. we From there, you then iterate the cursor and use the$set
update operator to add the new field to your documents using bulk operations for maximum efficiency.Aggregation query:
MongoDB 3.2 or newer
from this, you need to use the
bulkWrite
method.MongoDB 2.6 and 3.0
From this version you need to use the now deprecated
Bulk
API and its associated methods.MongoDB 2.4