【问题标题】:MongoDB / C# - Inserting document with an automatically populated timestampMongoDB / C# - 插入带有自动填充时间戳的文档
【发布时间】:2012-02-23 15:49:33
【问题描述】:

我正在尝试插入 MongoDB 集合。

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

从这里https://docs.mongodb.com/manual/reference/bson-types/#timestamps 我知道如果它们都为空,它们应该被自动填充?

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

我试过了:

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

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

谁能指出我正确的方向?

提前致谢

山姆

【问题讨论】:

    标签: c# mongodb nosql


    【解决方案1】:

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

    【讨论】:

    • 是的,这是我的问题。我的映射类(POCO 对象)有一个字符串 Id {get;set;} 和 long TimeStamp {get;set;} 作为前两个道具
    • 您确定没有其他隐藏字段吗? _id 或你的框架插入的东西。您是否通过运行 mongo shell 来查看条目?
    • 嗨 ivo,是的,我使用了 mongo shell 应用程序。前两个属性是_id 和时间戳。 (使用 db.collection.find() 我可以在文档对象中看到。)在我发布的链接中,我使用“new Timestamp()”引用了任何其他想法/想法?谢谢
    • 首先检查它是否在 mongo shell 中手动工作。 "db.foo.insert({x:new Timestamp() } )" 然后是 "db.foo.find()",你应该看到 "x" : { "t" : 1232423523523532, "i" : 1 } } .这将确认 mongodb 确实会自动填充时间戳。如果是这种情况,那么您的 POCO 对象有问题。我不使用 C#,所以帮不上忙。
    • 感谢您的评论,没有解决方案。我将解决方案更改为使用整数序列。 +1 回复但未回答问题。不过谢谢
    【解决方案2】:

    实际上无法在互联网上找到答案,因此花了一些时间才弄清楚如何去做。解决方案似乎很简单。当我尝试在控制台中输入new Timestamp() 时,它返回了Timestamp(0, 0),这对我来说是一个提示。您需要做的就是:

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

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

    【讨论】:

      【解决方案3】:
      //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")
      

      【讨论】:

        猜你喜欢
        • 2016-10-13
        • 1970-01-01
        • 2021-12-31
        • 2015-08-28
        • 2022-07-09
        • 2016-08-22
        • 2020-09-06
        • 1970-01-01
        • 2012-01-29
        相关资源
        最近更新 更多