1

I am trying to update documents of collection sale_order if sale_order['orderId'] exists in temp_sale_order. If it does not exists in temp_sale_order then a new document will be created in sale_order. (upsert).

But it only creates only one document in it.
If i use find instead of findOne. it throws an error:

Error:

uncaught exception: can't save a DBQuery object

My query:

db.getCollection('sale_order').update(
        db.getCollection('sale_order').find({},{orderId:1}),
        db.getCollection('temp_sale_order').findOne({},{orderId:1}),{upsert:true});

what is the correct way? Also how to write and use a function in mongodb with above query?

1 Answer 1

1

By default, update method updates only one document. You have to set the option "multi" : trueto update multiple documents at once.

http://docs.mongodb.org/manual/reference/method/db.collection.update/

db.getCollection('sale_order').update(
        db.getCollection('sale_order').find({},{orderId:1}),
        db.getCollection('temp_sale_order').findOne({},{orderId:1}),{upsert:true, multi:true});
Sign up to request clarification or add additional context in comments.

8 Comments

It says multi update only works with $ operators. I read about it but couldn't figure out how to use it with my query.
You only have access to mongoshell to achieve this ?
i am using mongodb on local server and using robomongo for the ide. I am running this query from robomongo
robomongo uses MongoShell wich is based on a Javascript engine, so you can use javascript loops in it. Following code will get all elements in temp_sale_order and will copy them in sale_order db.getCollection('temp_sale_order').find({}).forEach(function(element) { db.getCollection('sale_order').save(element); });
Can you tell me how to run this command from python. I am using pymongo and it is throwing me error
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.