2011-01-25 42 views
1

比方说,我有一个整数文档。如何更改MongoDB中的类型?

当我尝试将该值设置为3.5,它仍然整数

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

我怎样才能改变它漂浮/十进制?

+0

你在使用什么驱动程序? –

+0

2个问题:#1:*你是否真的打算更新一切*?如果是这样,你不使用多标志,为什么不呢? #2:你是从司机的外壳做这个的吗?如果是驾驶员,我们需要知道驾驶员。 –

回答

1

我只是做了一些例子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)); 
    } 

但是,如果你尝试自动desirialize测试类回更新后,它将引发错误,因为SomeIntegerField的类型将是Float64。所以对于这种情况,我建议编写单元测试。

希望这对你有所帮助。

+0

在这种情况下,反序列化器将引发TruncationException,因为存储在数据库中的值不能存储在Int32属性中,而不会损失精度。如果你想要的值是通过将3.5值截断为3来反序列化,那么你可以向SomeIntegerField添加一个属性:[BsonRepresentation(BsonType.Int32,AllowTruncation = true)]。 –

1

请检查update()语法。 update()的第一个参数始终是QUERY 而不是UPDATE子句。

+0

你说得对。这是一个错字。我在查询中使用了正确的一个。 – Alex