Updates.set doesn't work with List or Array value in mongo scala driver

751 views
Skip to first unread message

Wu Ming

unread,
Nov 12, 2016, 10:10:04 PM11/12/16
to mongodb-user
I want to update an array field value with mongo scala driver using Updates.set:

collection.updateOne(Filters.eq("foo", "hello"), Updates.set("bar", List("A", "B", "C")))

I got exception when running it:

Exception in thread "main" org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class scala.collection.immutable.$colon$colon.
at org.bson.codecs.configuration.CodecCache.getOrThrow(CodecCache.java:46)
at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:63)
at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:37)
at com.mongodb.client.model.BuildersHelper.encodeValue(BuildersHelper.java:35)
at com.mongodb.client.model.Updates$SimpleUpdate.toBsonDocument(Updates.java:442)
... 


I had tried changing the List to Array or other collection type, got same result.

The only solution that I know to work is by using Document object:

val updateDoc = Document("$set" -> Document("bar" -> List("A", "B", "C")))
collection
.updateOne(Filters.eq("foo", "hello"), updateDoc)

But it looks verbose.


Is Updates.set doesn't work with collection value or have I missed something here?

Ross Lawley

unread,
Nov 21, 2016, 4:42:01 AM11/21/16
to mongodb-user
Hi,

The issue here is there is no codec for Scala iterables. The wrapped  Updates.set("bar", List("A", "B", "C")) doesn't require any specific type for the value - so it won't be implicitly converted to a BsonValue like it is when you use the Scala document:  Document("$set" -> Document("bar" -> List("A", "B", "C")))

So the choices are use the java convertors to convert to a List or use the Scala Document type that uses special implicit convertors to ensure that all values can be transformed into a valid Bson Type.

There is a Scala ticket (SCALA-235) that adds a special Codec for Scala iterables and that is planned for release by the end of the month.

Ross
Reply all
Reply to author
Forward
0 new messages