0

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.

3
  • Here the selector would be auto generated id ---> Do you mean _id? Commented Jan 6, 2020 at 18:02
  • Why would you want to update without any selector for update command? Is there anything wrong with using a selector? Commented Jan 6, 2020 at 22:52
  • I will not require any selector here since im dealing with single document. Commented Jan 7, 2020 at 8:14

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

As you mentioned in the answer there is a mistake in syntax of the insert command in my question. Now i have updated the question.

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.