开发者

How to change type in MongoDB?

开发者 https://www.devze.com 2023-02-06 07:45 出处:网络
Let\'s say I have an integer document. When I try to set the value to 3.5, it still remains integer: db.users.update({}, {$set:{balance:3.5}})

Let's say I have an integer document.

When I try to set the value to 3.5, it still remains integer:

 db.users.update({}, {$set:{balance:3.5}})

How can I change it to float/dec开发者_开发技巧imal?


I've just done some example c#:

    public class Test
    {
       [BsonId]
       public string Id { get; set; }

       public int SomeIntegerField { get; set; }
    }

    [TestMethod]
    public void TypesTest()
    {
        var db = MongoRead.Instance;
        var collection = db.Database.GetCollection("test");
        var id = Guid.NewGuid().ToString();
        var test = new Test() { SomeIntegerField = 5, Id = id };
        collection.Insert(test);  //here type of SomeIntegerField in mongodb Integer

        //but after update type become Float64
        collection.Update(Query.EQ("_id", id), Update.Set("SomeIntegerField", 3.5));
  }

But if you try to automatically desirialize Test class back after update it will throw error, because type of SomeIntegerField will be Float64. So for such situations i suggest write unit tests.

Hope this help you.


Please check the update() syntax. The first parameter of update() is always THE QUERY not the UPDATE clause.

0

精彩评论

暂无评论...
验证码 换一张
取 消