Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mongodb

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

I simply want to update one field with the character count of another.

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

I've tried giving it dot notation

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

As well as using javascript syntax

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

But just copied the string and got a "notOkforstorage" respectively. Any help?

Update: I only get the "notOkforStorage" when I query by ID:

db.collection.update({_id:ObjectID("38289842bbb")},
                     {$set : {field1: {$where :"this.field2.length"}}})
like image 315
jwillis0720 Avatar asked Dec 23 '12 05:12

jwillis0720


People also ask

Is it possible to update MongoDB field using value of another field?

Starting from MongoDB 4.2 you can perform Updates with an Aggregation Pipeline. An aggregation pipeline enables more expressive updates including calculated fields and references to other field values in the same document.

How can we assign one field value to another in MongoDB?

MongoDB 3.2 and 3.0. The way we do this is by $project ing our documents and using the $concat string aggregation operator to return the concatenated string. 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.

What is Upsert in MongoDB update?

Upsert is a combination of insert and update (inSERT + UPdate = upsert). We can use the upsert with different update methods, i.e., update, findAndModify, and replaceOne. Here in MongoDB, the upsert option is a Boolean value. Suppose the value is true and the documents match the specified query filter.

How does update work in MongoDB?

The update() method updates the values in the existing document in the collections of MongoDB. When you update your document the value of the _id field remains unchanged. By default, the db. collection.


1 Answers

Try 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 part of the original collection do perform an update. If you want to process an 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 } } );
});
like image 54
Leonid Beschastny Avatar answered Sep 19 '22 18:09

Leonid Beschastny