Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I need help in updating MONGO DB. here is my document:

Functions : {
    "cgi0-app" : { 
        "calculatedConfigValues" : { 
            "floor" : 0.0 , 
            "ceiling" : 49.0 , 
            "calculatedBrokenValue" : 2.033 }, 
        "userConfigValues" : null }, 
    "shop-app" : { 
        "calculatedConfigValues" : { 
            "floor" : 0.0 , 
            "ceiling" : 70.0 , 
            "calculatedBrokenValue" : 2.413 } } }

I am trying to update shop-app's "ceiling" value from 70 to 100 in MongoDB, but not successful. Here is my Code:

BasicDBObject find = new BasicDBObject("Functions.shop app.calculatedConfigValues.floor",0);

BasicDBObject set = new BasicDBObject("$set", new BasicDBObject("Functions.shop-        app.calculatedConfigValues.$.ceiling", 100);

getDB().update(find, set);

Can someone please help me what I am doing wrong?

share|improve this question

migrated from programmers.stackexchange.com Apr 27 at 3:36

2 Answers

You can't really create DBObjects with that dot notation. You have to nest new BasicDBObjects for each level in the document tree.

DBObject toFind = new BasicDBObject("Functions", 
    new BasicDBObject("show-app", 
        new BasicDBObject("calculatedConfigValues", 
            new BasicDBObject("floor", 0))));

Same for the update object

DBObject update = new BasicDBObject("$set",
    new BasicDBObject("Functions", 
        new BasicDBObject("show-app", 
            new BasicDBObject("calculatedConfigValues",
                new BasicDBObject("ceiling", 100)))))

Alternatively, you can use this Helper class for translating json strings into DBObject structures like this.

DBObject toFind = (DBObject) JSON.parse(
    "{'Functions.show-app.calculatedConfigValues.floor':0}"
);

But be aware of that using the JSON class may cause performance problems. It's simply faster to build DBObjects manually.

share|improve this answer

Not sure if this will solve your problem, but don't you want to update a specific document within a collection within the DB? So something along these lines:

MongoClient mongo = new MongoClient();
DB db = mongo.getDB(DB_NAME);
db.getCollection(COLLECTION_NAME).update(find, set);

I would also define find in this way, because you want the specific object from that collection.

BasicDBObject obj = new BasicDBObject();
obj.put(..., 0);
DBObject find = db.getCollection(COLLECTION_NAME).findOne(obj);

Let me know if this works.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.