1

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/decimal?

1
  • 2 questions: #1: are you really intending to update everything? If so, you're not using the multiple flag, why not? #2: are you doing this from the shell of from a driver? If it's a driver, we'll need to know what driver. Commented Jan 25, 2011 at 23:50

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The deserializer will throw a TruncationException in this case because the value stored in the database cannot be stored in an Int32 property without loss of precision. If what you want is for the value to be deserialized without an exception by truncating the 3.5 value to 3 then you can add an attribute to the SomeIntegerField: [BsonRepresentation(BsonType.Int32, AllowTruncation = true)].
1

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

1 Comment

You are right. It was a typo. I used the right one in my query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.