1

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

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.