0

我有以下代码。EnsureIndexes 由构造函数调用,以确保已在 _expireAt 字段上创建 TTL 索引。然后,当通过调用 AddOrUpdateItem 方法插入文档时,它会将未来日期添加到 _expireAt 字段。但是,该日期过去了,文档永不过期。我究竟做错了什么?

private void EnsureIndexes()
    {
        if (!_indexChecked)
        {
            // TTL index
            var tsk = 
                MongoCollection.Indexes.CreateOneAsync(Builders<BsonDocument>.IndexKeys.Ascending("_expireAt"),
                        new CreateIndexOptions() { ExpireAfter = TimeSpan.FromSeconds(0) });

            tsk.Wait();

            _indexChecked = true;
        }
    }
public void AddOrUpdateItem(string key, TValue value, TimeSpan timeout)
    {
        var json = value.ToJson();
        dynamic jObject = JObject.Parse(json);
        jObject._expireAt = DateTime.UtcNow.Add(timeout);
        json = jObject.ToString();

        var replacementDocument = BsonSerializer.Deserialize<BsonDocument>(json);
        var filter = new BsonDocument("_id", key);
        var options = new UpdateOptions {IsUpsert = true};
        var tsk = MongoCollection.ReplaceOneAsync(filter, replacementDocument, options);

        try
        {
            tsk.Wait();
        }
        catch (AggregateException ex)
        {
            // TODO: Log

            throw;
        }
    }

以下内容与获取 Mongo 集合上的 getIndices 的命令一起返回。

> db.Users.getIndices()

[ {“v”:1,“key”:{“_id”:1},“name”:“ id ”,“ns”:“AuditDemo.Users”},{“v”:1,“key”: {“_expireAt”:1 },“名称”:“_expireAt_1”,“ns”:“AuditDemo.Users”,“expireAfterSeconds”:0 }] >

在我的 AddOrUpdateItem 方法中,我首先将泛型类型序列化为 json,以便能够为 expireAt 添加动态元素。然后我使用 BsonSerializer 将这个修改后的 json 反序列化为 BsonDocument。此时,BsonDocument 是否将 datetime json 字符串转换为 Bson 日期类型以使 TTL 索引起作用?

findOne 命令的结果

> db.Users.findOne({"_expireAt":{$exists: true}})

{“_id”:“0”,“UserGuid”:{“Value”:“054f6141-e655-41dd-a9d5-39382d3360ab”},“UserName”:null,“FirstName”:{“Value”:“JORDAN”} ,“姓氏”:{“价值”:“ACEVEDO”},“电子邮件”:{“价值”:“JORDAN.ACEVEDO@fake.com”},“__typ”:“AuditDemo.ConsoleApplication.Models.Wss.UserInfo, ConsoleTest 应用程序,版本=1.0.0.0,文化=中性,PublicKeyToken=null”,“_expireAt”:“2015-05-31T10:23:15.8979321Z”} >

4

1 回答 1

0

好的,我想出了如何纠正这个日期问题。我从 JSON.Net 获得的日期时间字符串没有存储 BSON 日期对象。所以我不得不在反序列化的 BsonDocument 属性上调用 BsonDateTime.create() 方法并强制它成为 BSON 日期。当它以正确的数据类型存储时,TTL 索引按预期工作。

        DateTime expiresDate = new DateTime(DateTime.UtcNow.Ticks, DateTimeKind.Utc).Add(timeout);
        var replacementDocument = BsonSerializer.Deserialize<BsonDocument>(json);
        replacementDocument["_expireAt"] = BsonDateTime.Create(expiresDate);
        var filter = new BsonDocument("_id", key);
        var options = new UpdateOptions {IsUpsert = true};
        var tsk = MongoCollection.ReplaceOneAsync(filter, replacementDocument, options);
于 2015-06-02T02:50:38.510 回答