更新int数组会在Mongo-shell中转换为双数组

Updating int array gets converted to double array in Mongo shell

本文关键字:数组 转换 int 更新 Mongo-shell      更新时间:2023-12-26

我有一个int数组要使用mongoshell在集合中更新。当我更新它时,它实际上以双重格式存储。

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 });  

实际上它存储了:

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

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

Mongoshell默认情况下将数字视为浮点值。所以,如果你想把它们当作其他东西来对待,就明确地告诉mongo。对于您的情况,您必须使用NumberInt()。

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

附言:你可能会发现我的另一个答案(类似)也很有用。