简体   繁体   中英

How can I update only new data or changed value in mongodb?

Update command updates the key with provided Json. I want to update only the object that is not present in db and changed value. How can I do that?

"data" : [ 
    {
        "_id" : "5bb6253d861d057857ec3ff0",
        "name" : "C"
    }, 
    {
        "_id" : "5bb625fc861d057857ec3ff1",
        "name" : "B"
    }, 
    {
        "_id" : "5bb625fe861d057857ec3ff2",
        "name" : "A"
    }
]

my data is like this. So, if one more array object comes in json of only 2 new object comes then it should insert the two data along with the 3 data.

Update the object that is not present in DB:

Use upsert : Upsert creates a new document when no document matches the query criteria. Alternatively, you can add null checks in your query eg { user_id:null }. This will allow to update the data where a record for the user is not present in DB.

Update changed value:

This can be implemented maintaining a key to store last_updated_at. If the last_updated_at value does not match to the previously_updatede_at that record can be treated at modified

You can implement Change Streams, introduced in MongoDB 3.6 from which you can receive real time changes on your data. You can receive only the data that was changed, filtering by the "update" operation. Furthermore you can also filter for data that is newly inserted filtering by the "insert" operation. Please see Change Streams .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM