MongoDB:如何为集合中的所有值运行某个字段的函数?

Rob*_*ezy 2 mongodb

我想从mongo shell做到这一点.基本上我想改变时间存储在当前数据库中的方式.

现在我的'时间'字段存储的字符串看起来像'2012年10月11日15:27:58 GMT-0500(CDT)',但我想运行Date.parse('Thu Oct 11 2012 15: 27:58 GMT-0500(CDT)')以便存储unix时间戳.

我想在所有当前条目中全面执行此操作,因为我将来会使用unix时间戳.

谢谢

pes*_*ira 5

怎么样:

var c = db.collection.find();
while (c.hasNext()) {
  object = c.next(); 
  time = Date.parse(object.time);
  db.collection.update({_id: object._id}, {$set: {'time': time}});
}
Run Code Online (Sandbox Code Playgroud)

在执行之前,我有以下内容:

db.times.find()
{ "_id" : ObjectId("50773daa77f428a7e4cd226b"), "time" : "Thu Oct 11 2012 15:27:58 GMT-0500 (CDT)" }
Run Code Online (Sandbox Code Playgroud)

执行后,它看起来像这样:

db.times.find()
{ "_id" : ObjectId("50773daa77f428a7e4cd226b"), "time" : 1349987278000 }
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!