0

this is my code to insert something to mongoDB

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

//i am using loop to get each object from list.

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(write);

when i tried this with price as string value no error.. i want to change price to double value for that i changed my price to double and then i changed my code as

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

but then error and telling me to change doc to double.. but i cant change doc to double because other values are string and it will again show error..

Please tell me how to insert double with other string values to mongoDB

I am a new to MongoDB

1
  • You can't replace append with getDouble, append is for setting mongo object value, getDouble(String attrName, double defaultValue) if for getting the double value within attribute attrName with a default value in case of attrName is missing. Commented Oct 24, 2014 at 10:22

1 Answer 1

0

As you have mixed types in one column you have to check for type before (this code is for reading a record):

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

Writing a new record should be straightforward, just use append the double value :

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

Of course Item must have getPrice() declared as :

public double getPrice() {return price;} 
Sign up to request clarification or add additional context in comments.

3 Comments

while i setprice to object i use double always.. so how can i insert a double value to mongoDB
String price="30"; item.setPrice(Double.parseDouble(price)); using this to set price ..
As simple as this : DBObject obj = new BasicDBObject().append("product_price", item.getPrice()). item.getPrice() have to return a double.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.