MongoDB update. Trying to set one field from a property of another

What I'm trying to do is pretty simple, but I can't find out how to give one field the value of another.

I just want to update one field with the number of characters of another.

db.collection.update({$exists:true},{$set : {field1 : field2.length}}) 

I tried to give it a dot notation

 db.collection.update({$exits:true},{$set : {field1: "this.field2.length"}}) 

Also using javascript syntax

 db.collection.update({$exits:true}, {$set : {field1: {$where : "this.field2.length"}}) 

But just copied the line and got "notOkforstorage" accordingly. Any help?

Update: I only get "notOkforStorage" when I request by ID:

 db.collection.update({_id:ObjectID("38289842bbb")}, {$set : {field1: {$where :"this.field2.length"}}}) 
+7
source share
3 answers

Try using the following code:

 db.collection.find(your_querry).forEach(function(doc) { doc.field1 = doc.field2.length; db.collection.save(doc); }); 

You can use your_querry to select only the part of the original collection that is performing the update. If you want to process the entire collection, use your_querry = {} .

If you want all operations to be atomic, use update instead of save :

 db.collection.find( your_querry, { field2: 1 } ).forEach(function(doc) { db.collection.update({ _id: doc._id },{ $set: { field1: doc.field2.length } } ); }); 
+15
source

As far as I know, the easiest way is to read and write aproach:

 //At first, get/prepare your new value: var d= db.yourColl.fetchOne({....}); d.field1== d.field2.length; // then update with your new value db.yourColl.save(d); 
0
source
  • Using exists is wrong. Syntax: { field: { $exists: <boolean> } }

  • You use $, where it is also incorrect
    Use the $ where operator to pass a query string containing a JavaScript expression or a full JavaScript function to the query system

    db.myCollection.find( { $where: "this.credits == this.debits" } ); db.myCollection.find( { $where: "obj.credits == obj.debits" } );

    db.myCollection.find( { $where: function() { return (this.credits == this.debits) } } );

    db.myCollection.find( { $where: function() { return obj.credits == obj.debits; } } );

I think you should use Map-Reduce for what you are trying to do.

-one
source

All Articles