user2325703
user2325703

Reputation: 1241

Mongodb update using Java

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?

Upvotes: 1

Views: 283

Answers (2)

rompetroll
rompetroll

Reputation: 4799

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.

Upvotes: 1

Mike Gostintsev
Mike Gostintsev

Reputation: 88

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.

Upvotes: 0

Related Questions