2012-01-15 29 views
6

Mi chiedo se esiste un modo per effettuare un aggiornamento autoreferenziale in MongoDB, quindi è possibile utilizzare i parametri dell'oggetto su una query $ set. Ecco un esempio:aggiornamento autoreferenziale tramite MongoDB

> 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" } 

ho visto che è possibile utilizzare questa sintassi in cui le 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); 

Così, ho provato con:

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

, ma non ha funzionato.

Il risultato atteso è:

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

Qualche idea? Grazie in anticipo

risposta

18

Attualmente non esiste un modo semplice per farlo. Ma puoi risolvere questo problema con

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

Grazie per la risposta RameshVel. Sto usando Mongoid, quindi analizzerò i risultati e li salverò con il vecchio valore. Sono preoccupato per la performance. Qualche raccomandazione? – fertapric

+0

@fertapric, sorry nope :(. Ho paura che sia l'unico modo. – RameshVel

+0

@RameshVel È ancora vero per la versione corrente di MongoDb? – Cartesius00