4

I'm trying to perform an update on an embedded document in MongoDB with the Java driver but receive an IllegalArgumentException that states "fields stored in the db can't have . in them"

My document has the structure:

{
    "_id" : ObjectId("5155d102a47d7b00b7e4bed2"),
    "foo" : {
        "bar" : {
            "name" : "Now"
        }
    }
}

and I want to perform an update like this

var query = {_id:ObjectId("5155d102a47d7b00b7e4bed2")};
var update = {"foo.bar.time":new Date()};
var withSet = {$set:update};
db.samples.update(query,withSet);

which from the console correctly modifies the document

{
    "_id" : ObjectId("5155d102a47d7b00b7e4bed2"),
    "foo" : {
        "bar" : {
            "name" : "Now",
            "time" : ISODate("2013-03-29T18:02:51.591Z")
        }
    }
}

Trying to do the same in Java I have not been successful. I've tried this:

BasicDBObject query = new BasicDBObject("_id", new ObjectId("5155d102a47d7b00b7e4bed2"));

BasicDBObject time = new BasicDBObject("time", new Date());
BasicDBObject bar = new BasicDBObject("bar", time);
BasicDBObject foo = new BasicDBObject("foo", bar);
BasicDBObject withSet = new BasicDBObject("$set", foo);

samples.update(query, withSet);

But it clobbers the embedded bar object, destroying name.

I've also tried:

BasicDBObject foo = new BasicDBObject();
foo.append("foo.bar.time", new Date());    
samples.update(query, foo)

But receive an IllegalArgumentException.

I've seen other answers chosen on Stack Overflow that include this dot notation. Is there something I'm missing? What is the proper way to update a field in an embedded document?

2
  • In your last example the $set part is missing, maybe this causes the problem. Try samples.update(query, new BasicDBObject("$set", new BasicDBObject("foo.bar.time", new Date()))); instead. Commented Mar 29, 2013 at 20:04
  • Glad it helped - I posted my comment as an answer so you could mark your question as solved. Commented Mar 29, 2013 at 21:08

1 Answer 1

6

In your last example the $set part is missing, maybe this causes the problem. Try

samples.update(
  query,
  new BasicDBObject(
    "$set",
    new BasicDBObject("foo.bar.time", new Date())
));

instead.

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.