更新int数组在Mongo shell中转换为double数组

Sum*_*eet 5 javascript mongodb mongo-shell

我有int数组使用mongo shell更新集合.当我更新它实际上它以双格式存储.

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 });  
Run Code Online (Sandbox Code Playgroud)

实际上它存储了:

{
  "_id" : ObjectId("529ae0e70971d81eedf5cb3d"),
  "path" : [1.0, 2.0, 3.0]
}
Run Code Online (Sandbox Code Playgroud)

我是mongo的新手,必须在mongo shell中运行更新查询.如何避免自动双转换.

Sal*_*ali 8

Mongoshell默认将数字视为浮点数.因此,如果您希望将它们视为其他内容,请明确告诉mongo.对于您的情况,您必须使用NumberInt().

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

PS你可能会发现我的另一个答案(类似的)也很有帮助.