Reputation: 4666
I have two collections(so and temp_so).
My query:
db.getCollection('temp_sale_order').find({},'orderItemId').
forEach(function(element) { db.getCollection('sale_order').save(element); });
i have a document with orderItemId
123 in temp_so. I want to check if a document with orderItemId
exist in so then the query should update the whole document in so. If the document with orderItemId does not exist in so, it should create one.
The query should do this for all the documents in temp_so.
My current query just insert the data in so and doesn't check if the document with orderItemId
exists or not in so. How to rectify it?
In SQL this can be written as:
insert into so ( select * from temp_so where orderItemId not in ( select orderItemId from so));
Update so set col = select col from temp_so where temp_so.orderItemId = so.orderItemId.
*update for all the columns*
Upvotes: 0
Views: 1470
Reputation: 50416
Technically speaking the .save()
action is already a "wrapper" around an "upsert", it's just only ever looking at the _id
field only, and where present.
So you just need to be explicit about which field you are looking up. And also removing the existing _id
:
db.getCollection('temp_sale_order').find({},{ 'orderItemId': 1 }).
forEach(function(element) {
delete element._id;
db.getCollection('sale_order').update(
{ "orderItemId": element.orderItemId },
element,
{ "upsert": true }
);
});
You might also consider that you don't want to replace the whole document and would rather just "insert" the first occurance only. Which is what $setOnInsert
does here:
db.getCollection('temp_sale_order').find({},{ 'orderItemId': 1}).
forEach(function(element) {
delete element._id;
db.getCollection('sale_order').update(
{ "orderItemId": element.orderItemId },
{ "$setOnInsert": { "orderItemid": element.orderItemId } },
{ "upsert": true }
);
});
So that basically means that any alteration within $setOnInsert
will not actually be applied unless this is actually an "upsert" and a new document is created. If it is just a "match" then nothing in the document gets changed.
Upvotes: 1