2

I am learning mongoDB.I have a collection which looks like this :

{
    "_id" : ObjectId("558cf353209c021b5a2fcbe5"),
    "term" : "gamma red eye tennis dampener",
    "year" : "2015",
    "month" : "05",
    "day" : "29",
    "hour" : "09",
    "dayofyear" : "176",
    "weekofyear" : "26",
    "productcount" : "1",
    "count" : "1"
}
{
    "_id" : ObjectId("578cf353209c021b5a2fcbe5"),
    "term" : "tennis dampener",
    "year" : "2015",
    "month" : "05",
    "day" : "29",
    "hour" : "09",
    "dayofyear" : "176",
    "weekofyear" : "26",
    "productcount" : "1",
    "count" : "7"
}
{
    "_id" : ObjectId("568cf353209c021b5a2fcbe5"),
    "term" : "gamma ",
    "year" : "2015",
    "month" : "05",
    "day" : "29",
    "hour" : "09",
    "dayofyear" : "176",
    "weekofyear" : "26",
    "productcount" : "1",
    "count" : "4"
}

Here the field count is String. I want to iterate through all the documents and convert it into INT using JAVA.

I am able to do it through console using this:

db.tq.find().forEach(function(obj) {
    obj.count= NumberInt(obj.count);
    db.tq.save(obj);
})

How to do it in java ?

1
  • Integer.parseInt(string) Commented Jun 26, 2015 at 6:57

1 Answer 1

5

You should do something like this -

DBCollection collection = db.getCollection("collection");
BasicDBObject document = new BasicDBObject();
DBCursor cursor = collection.find();
while (cursor.hasNext()) {
    DBObject cur = cursor.next();
    String id = cur.get("_id").toString();
    String c = cur.get("count").toString();
    int updateCount = Integer.parseInt(c);  //change to int
    BasicDBObject updateQuery = new BasicDBObject();
    updateQuery.append("$set", new BasicDBObject().append("count", updateCount));
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("_id", new ObjectId(id));
    collection.update(searchQuery, updateQuery);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.