Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update date field in mongo console?

Tags:

mongodb

For example I want to update all records to '2012-01-01' ( "time" : ISODate("2011-12-31T13:52:40Z") ).

db.test.update( { time : '2012-01-01' }, false, true  ) 

return error:

Assert failed : need an object Error("Printing Stack Trace")@:0 ()@shell/utils.js:35 ("assert failed : need an object")@shell/utils.js:46 (false,"need an object")@shell/utils.js:54 ([object Object],false,true)@shell/collection.js:189 @(shell):1  Wed Jan 11 17:52:35 uncaught exception: assert failed : need an object 
like image 253
Bdfy Avatar asked Jan 11 '12 14:01

Bdfy


People also ask

How do I change the date field in MongoDB?

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.

How do I update a single field in MongoDB?

To update a single field or specific fields just use the $set operator. This will update a specific field of "citiName" by value "Jakarta Pusat" that defined by $set operator.

Can we update document in MongoDB?

MongoDB's update() and save() methods are used to update document into a collection. The update() method updates the values in the existing document while the save() method replaces the existing document with the document passed in save() method.

How can I get current date in MongoDB query?

The current date in the MongoDB queryThe Date() will return the current date as a string. The new Date() will return the current date a date object and MongoDB cover the Date object with the ISODate.


1 Answers

You need to create a new ISODate object like this:

db.test.insert({"Time" : new ISODate("2012-01-10") }); 

This is true both for updates and for queries. Note that your query syntax is incorrect, it should be

db.test.update({ criteria }, { newObj }, upsert, multi); 

For example, to update all objects, consider

db.test.update( {}, { $set : { "time" : new ISODate("2012-01-11T03:34:54Z") } }, true, true); 

Also note that this is very different from

db.test.update( {}, { "time" : new ISODate("2012-01-11T03:34:54Z") }, true, false); 

because the latter will replace the object, rather than add a new field to the existing document or updating the existing field. In this example, I changed the last parameter to false, because multi updates only work with $ operators.

like image 117
mnemosyn Avatar answered Sep 30 '22 19:09

mnemosyn