2012-01-31 87 views
1

我试图插入到MongoDB集合中。MongoDB/C# - 插入带有自动填充时间戳的文档

我有一个数据模型包含Id(ObjectId)和时间戳(长)作为前两个属性。

从这里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); 

但随后得到 “GetDocumentId方法不能被称为一个UpdateWrapper。”例外。

任何人都可以指出我正确的方向吗?

在此先感谢

山姆

回答

1

时间戳必须是在你反对前两个领域之一,否则也不会得到填补。

+0

是的,这是我的问题。我的映射类(POCO对象)有一个字符串Id {get; set;}和long TimeStamp {get; set;}作为前两个道具 – sambomartin 2012-02-01 00:18:08

+0

您确定没有任何其他隐藏字段吗? _id或者你的框架插入的东西。您是否通过运行mongo shell来查看条目? – 2012-02-01 00:38:55

+0

嗨ivo,是的,我使用了mongo shell应用程序。前两个属性是_id和Timestamp。 (使用db.collection.find()我可以在文档对象中看到。)在链接中,我使用“new Timestamp()”发布了任何其他想法/想法的引用?谢谢 – sambomartin 2012-02-01 14:36:33

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); 

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