mongodb - MGO TTL 索引创建以选择性地删除文档

标签 mongodb go mgo ttl mongodb-indexes

我正在使用 Golang 和 MongoDB。我有一个集合需要保存一个可以持久或易变的文档。因此,如果它设置了一个过期日期(例如 expireAt),该文档将被认为是易变的并被删除,否则它将保留在集合中,除非它被手动删除。

阅读 this doc我找到了一个索引,它可能会在我需要时起作用。

基本上我需要在 mgo 中复制这种索引:

db.log_events.createIndex( { "expireAt": 1 }, { expireAfterSeconds: 0 } )

db.log_events.insert( {
  "expireAt": new Date('July 22, 2013 14:00:00'),
  "logEvent": 2,
  "logMessage": "Success!"
} )

我读过(我正在搜索此信息的来源)如果 expireAt 不是有效日期,则不会触发删除。因此我认为我需要做的就是在需要时将 expireDate 设置为有效日期,否则我会将其保留为 Go time.Time 零值。

这是我的代码库

type Filter struct {
    Timestamp time.Time     `bson:"createdAt"`
    ExpireAt  time.Time     `bson:"expireAt"`
    Body      string        `bson:"body"`
}

// Create filter from data received via REST API.
var filter Filter
timestamp := time.Now()

if theUserAction == "share" { // This is action will set the document as volatile
    filter.ExpireAt = time.Now().Add(24 * time.Hour * 14)
}

filter.Timestamp = timestamp
filter.Body = "A BODY"

// Store filter in database
session, err := mdb.GetMgoSession() // This is a wrapping method that returns a valid mgo session
if err != nil {
    return NewErrorInternal("Error connecting to database", err)
}
defer session.Close()


// Get db with global data for legent
collection := session.DB(database).C(filtersCollection)

我的问题是:如果 expireAt 键有效,我该如何设置索引以便删除文档? 阅读 mgo documentation about Index Type似乎没有办法复制先前声明的索引,因为该库仅提供 ExpireAfter 字段..

此外,假设零值可以被 mongodb 解释为无效日期是否有效?

根据文档,它是 January 1, year 1, 00:00:00.000000000 UTC 这实际上看起来像是一个有效日期..

到目前为止我的想法是做这样的事情:

filtIdx := mgo.Index{
    Key:        []string{"expireAt"},
    Unique:     false,
    Background: true,
    Sparse:     false,
    ExpireAfter: 0,
}

最佳答案

How can I set the index thus that it'll delete the document IF the expireAt key is valid?

使用 mgo.v2 设置 TTL 索引的示例如下:

index := mgo.Index{
    Key:         []string{"expireAt"},
    ExpireAfter: time.Second * 120, 
}
err = coll.EnsureIndex(index)

上面的示例设置为 120 秒的过期时间。另见 Expire Data from Collections by Setting TTL .

Is it still possible to make some documents to not expire at all? Since this is the behaviour I'm looking forward to obtain a collection where some documents do expire while other remain persistent

您可以为 ExpireAt 结构字段指定 omitempty 标志,如下所示:

type Filter struct {
    Timestamp time.Time `bson:"createdAt"`
    Body      string    `bson:"body"`
    ExpireAt  time.Time `bson:"expireAt,omitempty"`
}

如果字段未设置为零值,则基本上只包含该字段。查看更多信息 mgo.v2 bson.Marshal

现在,例如,您可以插入两个文档,其中一个将过期而另一个将继续存在。代码示例:

var foo Filter
foo.Timestamp = timestamp
foo.Body = "Will be deleted per TTL index"
foo.ExpireAt = time.Now()
collection.Insert(foo)

var bar Filter
bar.Timestamp = timestamp
bar.Body = "Persists until expireAt value is set"
collection.Insert(bar)

稍后,您可以使用 Update() 设置 expireAt 字段,例如:

newValue := bson.M{"$set": bson.M{"expireAt": time.Now()}}
err = collection.Update(queryFilter, newValue)

expireAt 字段设置一个有效的时间值,将使其符合 TTL 索引。即不再存在。

根据您的用例,您也可以选择 Remove()文档而不是更新和依赖 TTL 索引。

关于mongodb - MGO TTL 索引创建以选择性地删除文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36720669/

相关文章:

mongodb - 确保 MongoDB 以动态时间间隔使数据过期并且调用是幂等的

MongoDB - 如何在配置文件中使用 setParameter

node.js - 使用 MongoDB 进行单元测试查询

javascript - MERN React/Redux/MongoDB 带身份验证的实体同构样板

tree - Golang 中的这段代码是惯用的吗?持久化树

mongodb - 如果slice存在,并且它包含至少一个设置为true的特定变量

mongodb - Golang mongodb mgo 驱动 Upsert/UpsertId 文档

javascript - NodeJS MongoDB 适配器将字符串解释为文字而不是值

go - 如何从 Gcloud beta 模拟器 firestore 中删除所有文档?

go - 使用 mgo 错误插入 ISODate 字段