Rakesh Sankar
Rakesh Sankar

Reputation: 9415

What is the MongoDB equivalent of an UPDATE SQL which updates a record with existing field value

I have this following SQL and I would like to know the MongoDB equivalent.

update tblName set kwatt = kwatt/3600000 where kwatt is not null.

Note:

I know we can write a JS function in the server and get this done, I want this to be done from PHP driver and I am not sure how can I do this easily.

Please help.

Upvotes: 2

Views: 382

Answers (2)

Fatih Donmez
Fatih Donmez

Reputation: 4347

Actually you can do it with both combining findAndModify and stored javascript together..

Create a stored function for division like ;

db.system.js.save({_id: "div",
             value: function (x, y) { return x/y; }});

Then in findAndModify something like ;

findAndModify({query:{id:1},update:{$set:{id:"div(this.id,5)"}}});

It's just for idea, I didnt test it..

Stored Javascript Sample

Upvotes: 3

user2665694
user2665694

Reputation:

You can not perform this in one database operation. You need to query for the related rows first and then perform an additional update operation on each row. It is not possible to update the value of a document with the value of a result row within one database operation. The rest is up to you and straight forward.

Upvotes: 1

Related Questions