Self-regulatory update using MongoDB

I wonder if there is a way to do a self-referenced update in MongoDB, so you can use the object parameters in the $ set request. Here is an example:

> db.labels.save({"name":"label1", "test":"hello"}) > db.labels.save({"name":"label2", "test":"hello"}) > db.labels.save({"name":"label3", "test":"hello"}) > db.labels.find() { "_id" : ObjectId("4f1200e2f8509434f1d28496"), "name" : "label1", "test" : "hello" } { "_id" : ObjectId("4f1200e6f8509434f1d28497"), "name" : "label2", "test" : "hello" } { "_id" : ObjectId("4f1200eaf8509434f1d28498"), "name" : "label3", "test" : "hello" } 

I saw that you can use this syntax for $ where query: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-JavascriptExpressionsand%7B%7B%24where%7D%7D

 > db.myCollection.find( { a : { $gt: 3 } } ); > db.myCollection.find( { $where: "this.a > 3" } ); > db.myCollection.find("this.a > 3"); > f = function() { return this.a > 3; } db.myCollection.find(f); 

So I tried:

db.labels.update ({"test": "hola"}, {$ set: {"test": this.name})

but it didn’t work.

Expected Result:

 { "_id" : ObjectId("4f1200e2f8509434f1d28496"), "name" : "label1", "test" : "label1" } { "_id" : ObjectId("4f1200e6f8509434f1d28497"), "name" : "label2", "test" : "label2" } { "_id" : ObjectId("4f1200eaf8509434f1d28498"), "name" : "label3", "test" : "label3" } 

Any thoughts? thanks in advance

+6
source share
1 answer

There is currently no direct way to do this. But you can get around this with

  db.labels.find({"test":"hola"}).forEach(function (doc) { doc.test = doc.name; db.labels.save(doc); }) 
+18
source

Source: https://habr.com/ru/post/906019/


All Articles