[英]How to avoid changes to field data type in MongoDB?
I'm new to MongoDB and I'm starting a new project with Spring Data MongoDB. 我是MongoDB的新手,并且正在使用Spring Data MongoDB启动一个新项目。
I created a simple model POJO and I inserted some documents into products
collection: 我创建了一个简单的模型POJO,并将一些文档插入了products
集合:
@Document(collection="products")
public class Product {
@Id
private String id;
private String name;
private double price;
private int quantity;
// ...
}
In my DB field types are mapped correctly: 在我的数据库字段类型正确映射:
name
to String
, name
为String
, price
to Double
, price
Double
, quantity
to Int32
quantity
到Int32
But making some test i tried to increment quantity
field via $inc
modifier: 但是做一些测试,我试图通过$inc
修饰符增加quantity
字段:
db.products.update({"name" : "A product"}, {"$inc" : {"quantity" : 1}});
and now quantity
field type is changed to Double
. 现在quantity
字段类型更改为Double
。
How can I avoid this? 如何避免这种情况?
Thanks to Neil Lunn comment, I realized that a way to keep the same data type for my quantity
field is to explicitly specify the type of the increment amount. 感谢Neil Lunn的评论,我意识到为我的quantity
字段保持相同数据类型的一种方法是显式指定增量数量的类型。
In this case I have an Int32
so I can use this code to update it: 在这种情况下,我有一个Int32
因此可以使用以下代码对其进行更新:
db.products.update({"name" : "A product"}, {"$inc" : {"quantity" : NumberInt(1)}});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.