Miller
Miller

Reputation: 744

How to update second value in mongodb?

I am new to Mongodb.I am totally confused how to update it.I have a field named price.I need to update it by REMOVING THE USD from my price field.Below is an example .....But 620(will varies for different objects) must have to stay there.Can anyone please help.Any help will be highly appreciable.

{
  "_id" : 1234,
  "price" :"620.0,USD",
  "description" : "Awesome"
}

into

{
  "_id" : 1234,
  "price" :"620.0",
  "description" : "Awesome"
}

Advance thanks .......

Upvotes: 0

Views: 60

Answers (2)

Miller
Miller

Reputation: 744

I myself found the solution.

while(cursor.hasNext())
       {
          BasicDBObject doc=(BasicDBObject) cursor.next();
          String s=doc.getString("product_price").split("[,]")[0];
          String s1=doc.getString("product_img").split("[,]")[0];
          Double price=Double.parseDouble(s);

          doc.append("$set",new BasicDBObject().append("product_price", price).append("product_img",s1));

         BasicDBObject updateQuery = new BasicDBObject();
        updateQuery.append("$set", 
            new BasicDBObject().append("product_price", price).append("product_img",s1));

        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.append("product_id", doc.getString("product_id"));
     System.out.println(doc.getString("product_id"));

        coll.updateMulti(searchQuery, updateQuery);
//      System.exit(1);
        System.out.println("completed");

By using this above code i solved my problem...Thanku

Upvotes: 1

Neo-coder
Neo-coder

Reputation: 7840

Thisthings not possible directly through mongo query so may be you need to used java script so below code will solve your problem

db.collectionName.find({
    "_id": 1234,
    price: {
    $regex: '^[
        0-9
    ]',
    $options: 'i'
    }
}).forEach(function(doc){
    varupdatedPrice=doc.price.replace(/[
    ^0-9\.
    ]+/g,
    "");
   db.price.update({
    "_id": doc._id
    },
    {
    "$set": {
        "price": updatedPrice
    }
    });
})

Upvotes: 1

Related Questions