Java driver - updating a field with a Map or an enum

1,048 views
Skip to first unread message

Paul Gifford

unread,
Dec 12, 2015, 12:09:49 PM12/12/15
to mongodb-user
Hi,
 
  I'm using Java driver 3.1.0.  I have a document with a field ("myMapField") that is populated with a Map<String, Object>.  I am able to insert the document (as a Document) but I can't update the field.  Here's how I'm trying to update the field:

myCollection.updateOne(filter, set("myMapField", myMap));



  I get the following exception:

org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class java.util.HashMap.
    at org.bson.codecs.configuration.CodecCache.getOrThrow(CodecCache.java:46) ~[bson-3.1.0.jar:na]


  Looking at the source code I see why I'm able to insert but not update: org.bson.codecs.DocumentCodec encodes a Map by iterating over the EntrySet, writing each value individually.  com.mongodb.client.model.BuildersHelper takes a different approach and looks in the registry for the class, hence the exception.  The same thing happens with enums - I can insert an enum but can't update a field with an enum.

  Is there some reason updates are different than inserts?  BuildersHelper is final so it can't be extended, though there's probably no way to insert a custom BuildersHelper anyway.  It would really be helpful if BuildersHelper took the same approach as DocumentCodec when encoding values.

Paul



 


Ross Lawley

unread,
Dec 14, 2015, 5:30:33 AM12/14/15
to mongod...@googlegroups.com
Hi,

This is a because the Updates.Set helper doesn't support complex data types - see JAVA-2056 so it fails to convert to it correctly.

If you try without the helper it should work as expected eg:

myCollection.updateOne(filter, new Document("$set"new Document("myMapField", myMap)));

Hope that helps,

Ross

--
You received this message because you are subscribed to the Google Groups "mongodb-user"
group.
 
For other MongoDB technical support options, see: http://www.mongodb.org/about/support/.
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user...@googlegroups.com.
To post to this group, send email to mongod...@googlegroups.com.
Visit this group at https://groups.google.com/group/mongodb-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-user/a7fb689b-5237-4e52-a964-9ea4aa70d90f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--


{ name     : "Ross Lawley",
  title    : "Senior Software Engineer",
  location : "London, UK",
  twitter  : ["@RossC0", "@MongoDB"],
  facebook :"MongoDB"}

Reply all
Reply to author
Forward
0 new messages