How to do bulk updates of documents with values they already contain?

1,002 views
Skip to first unread message

DavidJBerman

unread,
Mar 22, 2012, 10:49:45 AM3/22/12
to mongod...@googlegroups.com
I have a collection with a lot of documents in it.  Each document has a field "tsAdded" which is a time stamp of when the document was created and added to the collection.  Now I want to add a new field, tsModified, a time stamp of when the document was last modified.  I realized I want to sort my documents by tsModified, not tsCreated, but I want to preserve my tsAdded value.  What I want to do initially is update all my documents to add the tsModified field and set the value of tsModified = tsAdded, so I can sort by tsModified right away.

In SQL to achieve this I would do something like this:
UPDATE docs
    set tsModified = tsAdded

Is it possible to do something like this in Mongo, such that Mongo will update all documents in my collection and set one field value equal to the value of another field in the same document?

Thank you.

David

何健

unread,
Mar 22, 2012, 11:14:34 AM3/22/12
to mongod...@googlegroups.com
Does this meet your needs?

MongoDB shell version: 2.1.1-pre-
connecting to: test
> db.blog.find()
{ "_id" : 1, "tsAdded" : ISODate("2012-03-22T15:05:58.671Z") }
{ "_id" : 2, "tsAdded" : ISODate("2012-03-22T15:05:59.234Z") }
> db.blog.find().forEach(function(doc){doc.tsModified = doc.tsAdded;db.blog.save
(doc)})
> db.blog.find()
{ "_id" : 1, "tsAdded" : ISODate("2012-03-22T15:05:58.671Z"), "tsModified" : ISO
Date("2012-03-22T15:05:58.671Z") }
{ "_id" : 2, "tsAdded" : ISODate("2012-03-22T15:05:59.234Z"), "tsModified" : ISO
Date("2012-03-22T15:05:59.234Z") }

Thanks,
HE Jian

在 2012年3月22日星期四UTC+8下午10时49分45秒,DavidJBerman写道:

DavidJBerman

unread,
Mar 22, 2012, 11:19:42 AM3/22/12
to mongod...@googlegroups.com
Jian,
  This looks to be exactly what I needed.  I'll give this a try.  Thank you very much!

David

Scott Hernandez

unread,
Mar 22, 2012, 11:20:39 AM3/22/12
to mongod...@googlegroups.com
Yes, you must update each document individually after reading them.
You can also use $set to just change the one field, for example.

http://www.mongodb.org/display/DOCS/Updating

> --
> You received this message because you are subscribed to the Google Groups
> "mongodb-user" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/mongodb-user/-/LuzuLmBDicEJ.
>
> To post to this group, send email to mongod...@googlegroups.com.
> To unsubscribe from this group, send email to
> mongodb-user...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/mongodb-user?hl=en.

Reply all
Reply to author
Forward
Message has been deleted
0 new messages