self referencing update using MongoDB
new in MongoDB 4.2
[FYI] Below approach avoids row-by-row operations (which can cause performance issues), and shifts the processing load onto the DB itself.
"Starting in MongoDB 4.2, the db.collection.update() method can accept an aggregation pipeline that specifies the modifications to perform." docs
The pipeline has access to each documents' fields, thus allowing self-referencial updates.
Please see the documentation on this, which includes an example of this sort of update.
Following the example from the OP's question the update would be:
db.labels.update(
{"test":"hello"},
[{ $set: { test: "$name" }}],
{ multi: true }
);
Please note that the $set
used in the pipeline refers to the aggregation stage $set
, and not the update operator $set
.
For those familiar with the aggregate pipeline in earlier MongoDB versions: the $set
stage is an alias for $addFields
.
Update:
It can be done by now using
db.labels.updateMany(
{"test":"hola"},
[{ $set: { test: "$name" }}],
)
Old Answer
At present there is no straight way to do that. But you can workaround this by
db.labels.find({"test":"hola"}).forEach(function (doc) {
doc.test = doc.name;
db.labels.save(doc);
})