Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

mongodb - How to update date field in mongo console?

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
question from:https://stackoverflow.com/questions/8821206/how-to-update-date-field-in-mongo-console

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...