How to apply the update after reading the existing document

Before I update the document, I want to first retrieve the value of the existing document, such as:
document A:

{
id: 22893472347102,
apple: 3,
count: 5
}

I want to update {apple: 5, count:3} to document A, if apple in document A == 3, else insert {apple: 2, count:5}.
Is there any way to do it faster without doing query + insert(two action)?

Your request is not clear to me.

You want to update but you write

Do you want to update or insert?

It is best to share sample income documents and sample output documents.

I want to update, but base on the existing document content to update, I don’t want to use .find then use .updateOne, is there any faster solution that I can base on existing document to update?

Doing a find() then an updateOne() is definitively the wrong way to do it.

Yes there is. But with the scarce details of what you exactly want to do, the only thing we can do is to send you to the documentation on update operators:

A much better answer could be supplied with:

Existing document A:

{
id: 22893472347102,
type: "apple",
count: 10,
needReduce: 2,
}

Sample update:

Model.updateOne({type: "apple"}, {count: 20})

Sample document A after updated(count should reduce the existing needReduce value):

{
id: 22893472347102,
type: "apple",
count: 18,
needReduce: 2,
}

How can I do it without .find({type: apple}), then .updateOne()?

From the sample documents and update desired you need to use updateOne() using the update with aggregation:

A $set, that uses $subtract such as the untested:

update = { count : 20 } ;
Model.updateOne( 
    { "type" : "apple" } ,
    [ { "$set" : {
        "count" : { "$subtract" : [ update.count , "$needReduce" ] }
    } } ]
) ;

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.