MongoDB / C# - 插入带有自动填充时间戳的文档

问题描述 投票:1回答:3

我正在尝试插入MongoDB集合。

我有一个包含Id(ObjectId)和Timestamp(long)的数据模型作为前两个属性。

从这里https://docs.mongodb.com/manual/reference/bson-types/#timestamps我明白如果这些都是null,它们应该自动填充?

保存实体时,正在设置ObjectId(Id / _id)列,但时间戳保持为空。我需要做些什么特别的设置吗?

我试过了:

    newdoc= Update.Replace(doc.ToBsonDocument().Set("Timestamp", new BsonJavaScript("new Timestamp()")));
    db.mydocs.Save(newdoc);

但随后得到“无法在UpdateWrapper上调用GetDocumentId方法”。例外。

有人能指出我正确的方向吗?

提前致谢

他自己

c# mongodb nosql
3个回答
1
投票

时间戳必须是您对象中的前两个字段之一,否则它将不会被填充。


0
投票
//Use C# native DateTime Library
var dateTime = DateTime.UtcNow;

//Filter 
var filter = builder.Eq("SomeKey", "SomeValue");

//What needs to be updated
var update = Builders<BsonDocument>.Update                  
.Set("createdAt", dateTime);

//Upsert Option!
var options = new UpdateOptions { IsUpsert = true };

collection.UpdateMany(filter, update, options)

//Out Put
"createdAt" : ISODate("2016-12-21T19:25:22.471Z")

0
投票

无法在互联网上找到答案,所以花了一些时间才弄清楚如何做到这一点。解决方案似乎非常简单。当我试图在控制台中输入new Timestamp()时,它返回了Timestamp(0, 0),这对我来说是个暗示。你需要做的就是:

doc.Timestamp = new BsonTimestamp(0, 0);

这将使服务器为您设置时间戳的值。

© www.soinside.com 2019 - 2024. All rights reserved.