Golang/mgo:我如何要求MongoDB在一个字段中使用当前时间?

huangapple go评论96阅读模式
英文:

Golang/mgo: How can I ask MongoDB to use current time in a field?

问题

我有一个与我正在使用的MongoDB集合的类型匹配的结构体:

type AppInstance struct {
    Id bson.ObjectId "_id,omitempty"
    Url string
    Priority int
    LastSeen string
}

我希望LastSeen字段保存与该特定应用程序的最后交互的时间。因此,该应用程序在设置当前时间(作为字符串)时会注册自己。

我想要的是Mongo在插入时动态地将自己的当前时间设置到该字段中,就像MySQL的NOW()函数一样。

我有这个辅助函数:

func mongoNow() bson.JavaScript {
    return bson.JavaScript{Code: 
         "return (new Date()).ISODate('YYYY-MM-DD hh:mm:ss');"}
}

我尝试了这个:

c := mongoSession.DB("myapp").C("instances")
rand.Seed(time.Now().UnixNano())
err := c.Insert(
   struct{Id, Serial, Priority, Url, LastSeen interface{}}{ 
      Id: bson.NewObjectId(), 
      Url: getInformedHost() + ":" + getRunningPortString(), 
      Priority: rand.Int(), 
      LastSeen: mongoNow() }
)
checkError(err, "Could not register on MongoDB server.", 3)

LastSeen字段被存储为脚本而不是被评估:

[_id] => MongoId Object (
    [$id] => 502d6f984eaead30a134fa10
)
[id] => MongoId Object (
    [$id] => 502d6f98aa443e0ffd000001
)
[priority] => 1694546828
=> 127.0.0.1:8080 [lastseen] => MongoCode Object ( [code] => (new Date()).ISODate('YYYY-MM-DD hh:mm:ss') [scope] => Array ( ) )

所以,我认为有两个问题:

首先,如何插入当前时间?

其次,如何获取一些JavaScript代码的评估结果而不是插入?

对第二个问题的答案可能足以回答第一个问题,但也可能不足够。

英文:

I have this struct that matches the types of a MongoDB collection I'm using:

type AppInstance struct {
    Id bson.ObjectId "_id,omitempty"
    Url string
    Priority int
    LastSeen string
}

I want the LastSeen field to hold the time of the last interaction with that particular app. So, the app registers itself setting current time (as a string).

What I would like is Mongo to dynamically set its own current time into that field when it inserts, just like MySQL's NOW() function would do.

I have this helper function:

func mongoNow() bson.JavaScript {
    return bson.JavaScript{Code: 
         "return (new Date()).ISODate('YYYY-MM-DD hh:mm:ss');"}
}

And I tried this:

c := mongoSession.DB("myapp").C("instances")
rand.Seed(time.Now().UnixNano())
err := c.Insert(
   struct{Id, Serial, Priority, Url, LastSeen interface{}}{ 
      Id: bson.NewObjectId(), 
      Url: getInformedHost() + ":" + getRunningPortString(), 
      Priority: rand.Int(), 
      LastSeen: mongoNow() }
)
checkError(err, "Could not register on MongoDB server.", 3)

the LastSeen field gets stored as a script instead of evaluated:

[_id] => MongoId Object (
    [$id] => 502d6f984eaead30a134fa10
)
[id] => MongoId Object (
    [$id] => 502d6f98aa443e0ffd000001
)
[priority] => 1694546828
=> 127.0.0.1:8080 [lastseen] => MongoCode Object ( [code] => (new Date()).ISODate('YYYY-MM-DD hh:mm:ss') [scope] => Array ( ) )

So, I think there are to questions:

First, how can I insert the current time?

Second, how can I get some javascript evaluated instead of inserted?

The answer to the second one could be enough to answer the first one, but it might as well not be.

答案1

得分: 44

不要将时间存储为字符串。mgo支持time.Time,它类似于Javascript中的Date对象:

type Event struct {
    Id    bson.ObjectId "_id,omitempty"
    Which string
    Date  time.Time
}

插入一个当前发生的事件:

e := Event{
    Which: "第一个事件",
    Date: time.Now(),
}
c.Insert(e)
英文:

Don't store time as string. mgo supports time.Time which is like a Date object in Javascript:

type Event struct {
    Id    bson.ObjectId "_id,omitempty"
    Which string
    Date  time.Time
}

Insert an event that happened now:

e := Event{
    Which: "first event",
    Date: time.Now(),
}
c.Insert(e)

答案2

得分: 5

在Mongo 2.6中,您可以使用$currentDate运算符来实现。

db.users.update( { _id: 1 }, {
   $currentDate: {
     lastModified: true,
     lastModifiedTS: { $type: "timestamp" }
   },
   $set: { status: "D" }
})
英文:

In Mongo 2.6 you can do it natively with $currentDate operator.

db.users.update( { _id: 1 }, {
   $currentDate: {
     lastModified: true,
     lastModifiedTS: { $type: "timestamp" }
   },
   $set: { status: "D" }
})

huangapple
  • 本文由 发表于 2012年8月17日 07:07:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/11996693.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定