Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating int array gets converted to double array in Mongo shell

I have int array to update in collection using mongo shell .When I update it actually it stores in double format .

var  array =[1,2,3];     // int array as all elements are int 
                         // Update query where path is the collection field
 db.doc.update({},{$set : {“path”:array}},{ upsert: true });  

Actually it stored:

{
  "_id" : ObjectId("529ae0e70971d81eedf5cb3d"),
  "path" : [1.0, 2.0, 3.0]
}

I am novice to mongo and have to run update query in mongo shell. How to avoid auto double conversion.

like image 579
Sumeet Kumar Yadav Avatar asked Dec 01 '13 07:12

Sumeet Kumar Yadav


People also ask

How do I update an array in MongoDB?

You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.

How do I update a nested array in MongoDB?

Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades.

How do I update multiple elements in MongoDB?

Update Multiple Fields of a Single Document. We can use $set and $inc operators to update any field in MongoDB. The $set operator will set the newly specified value while the $inc operator will increase the value by a specified value.

How do I change the datatype of a field in MongoDB?

You can change the data type of a field by using the data type selectors on the right of the field in the Atlas Cloud Cluster as well as MongoDB Compass . If you want to update it using Mongo shell or any specific drivers of MongoDB then you can refer to the $convert operator.


1 Answers

Mongoshell treats numbers as float by default. So if you want them to be treated as something else, tell this to mongo explicitly. For your case, you have to use NumberInt().

So var array = [NumberInt("1"), NumberInt("2"), NumberInt("3")];

P.S. you might find my another answer (which is similar) helpful as well.

like image 88
Salvador Dali Avatar answered Oct 23 '22 06:10

Salvador Dali