简体   繁体   中英

How to update a mongodb collection with single document using pymongo?

If i create a collection with single document using:

db.time_data.insert({"Last_updated":"Jan 6 22:19:48 IST","Next_scheduled":"Jan 6 23:19:48 IST"})

How can i update the Last_updated and Next_scheduled fields ? I would like to do it without using any selector for update command. Here the selector would be auto generated id.

Not sure how you've created a document using :

db.time_data.insert({"Last_updated":"Jan 6 22:19:48 IST"},{"Next_scheduled":"Jan 6 23:19:48 IST"})

cause that operation will result in document being created like this :

/* 1 */
{
    "_id" : ObjectId("5e1374692a0e7dc716ae47fa"),
    "Last_updated" : "Jan 6 22:19:48 IST"
}

It's quiet normal as second object {"Next_scheduled":"Jan 6 23:19:48 IST"} is ignored, your query should be like below in-order to create a single document with two fields :

db.time_data.insert({"Last_updated":"Jan 6 22:19:48 IST","Next_scheduled":"Jan 6 23:19:48 IST"})

Update :

Since your collection has only one document, to update it you don't really need any filter, you just do :

db.time_data.update({}, {"Last_updated":"Jan 7 22:19:48 IST","Next_scheduled":"Jan 7 23:19:48 IST"})

(Or)

db.time_data.updateOne({}, {$set :{"Last_updated":"Jan 8 22:19:48 IST","Next_scheduled":"Jan 8 23:19:48 IST"}})

(Or)

db.time_data.findOneAndUpdate({}, {$set :{"Last_updated":"Jan 9 22:19:48 IST","Next_scheduled":"Jan 9 23:19:48 IST"}})

So you could use any of above or even .updateMany() depends on need, check for their responses some return write result Vs some do return updated document(If you set option to return new document). These queries are for mongoDB shell, please search for update in pymongo Ref link to get these converted to work with python(Most basic changes will be syntax thing like updateOne to update_one , updateMany to update_many , also do check on options being passed with these as they may vary from mongoDB shell to drivers like pymongo / mongoDB driver / mongoose ).

MongoDB Ref : update , .findOneAndUpdate()

pymongo Ref : pymongo-doc

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