【问题标题】:how to insert double and string values to MongoDB如何将双精度值和字符串值插入 MongoDB
【发布时间】:2014-12-20 04:03:27
【问题描述】:

这是我向 mongoDB 插入内容的代码

List<DBObject> write=new ArrayList<DBObject>();   //write is a list of objects

//我正在使用循环从列表中获取每个对象。

DBObject doc = new BasicDBObject("product_name", item.getName()).
                            append("product_url", item.getUrl()).
                            append("product_img", item.getImage()).
                            append("product_price", item.getPrice()).
                            append("time",item.getTime()).
                            append("category", item.getCategory());
write.add(doc);

// t = db.getCollection(table); t.insert(写);

当我尝试将价格作为字符串值时没有错误.. 我想将价格更改为双倍值,因为我将价格更改为双倍,然后我将代码更改为

getdouble("product_price", item.getPrice());  //used this instead of .append

然后出错并告诉我将 doc 更改为 double.. 但我无法将 doc 更改为 double 因为其他值是字符串,它会再次显示错误..

请告诉我如何将带有其他字符串值的双精度值插入 mongoDB

我是 MongoDB 新手

【问题讨论】:

  • 您不能用 getDouble 替换 append,append 用于设置 mongo 对象值,getDouble(String attrName, double defaultValue) 如果用于在 attrName 的情况下使用默认值获取属性 attrName 中的 double 值不见了。

标签: java mongodb mongodb-query database


【解决方案1】:

由于您在一列中混合了类型,因此您必须在之前检查类型(此代码用于读取记录):

if(obj.get("product_price") instanceof String) {
    item.setPrice(Double.parseDouble((String)obj.get("product_price")));
} else {
    item.setPrice(obj.getDouble("product_price"));
}

写入新记录应该很简单,只需使用附加双精度值:

DBObject doc = new BasicDBObject("product_name", item.getName()).
                            append("product_url", item.getUrl()).
                            append("product_img", item.getImage()).
                            append("product_price", item.getPrice()).
                            append("time",item.getTime()).
                            append("category", item.getCategory());
write.add(doc);

当然,Item 必须将 getPrice() 声明为:

public double getPrice() {return price;}

【讨论】:

  • 当我将价格设置为对象时,我总是使用双精度.. 那么如何将双精度值插入 mongoDB
  • 字符串价格="30"; item.setPrice(Double.parseDouble(price));用它来设定价格..
  • 就这么简单:DBObject obj = new BasicDBObject().append("product_price", item.getPrice())。 item.getPrice() 必须返回一个双精度值。
猜你喜欢
  • 1970-01-01
  • 2011-08-11
  • 2011-03-22
  • 2016-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多