Note that there are some explanatory texts on larger screens.

plurals
  1. POUpdating fields in embedded documents with MongoDB Java Driver?
    text
    copied!<p>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"</p> <p>My document has the structure:</p> <pre><code>{ "_id" : ObjectId("5155d102a47d7b00b7e4bed2"), "foo" : { "bar" : { "name" : "Now" } } } </code></pre> <p>and I want to perform an update like this</p> <pre><code>var query = {_id:ObjectId("5155d102a47d7b00b7e4bed2")}; var update = {"foo.bar.time":new Date()}; var withSet = {$set:update}; db.samples.update(query,withSet); </code></pre> <p>which from the console correctly modifies the document</p> <pre><code>{ "_id" : ObjectId("5155d102a47d7b00b7e4bed2"), "foo" : { "bar" : { "name" : "Now", "time" : ISODate("2013-03-29T18:02:51.591Z") } } } </code></pre> <p>Trying to do the same in Java I have not been successful. I've tried this:</p> <pre><code>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); </code></pre> <p>But it clobbers the embedded bar object, destroying name.</p> <p>I've also tried:</p> <pre><code>BasicDBObject foo = new BasicDBObject(); foo.append("foo.bar.time", new Date()); samples.update(query, foo) </code></pre> <p>But receive an IllegalArgumentException.</p> <p>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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload