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?