Search code examples
scalacasbah

java.lang.IllegalArgumentException: BasicBSONList can only work with numeric keys, not: [_id]


After another SO poster(Vinicius Miana) resolved my issue to insert a List[DBObject] ...

// Bulk insert all documents
collection.insert(MongoDBList(docs)) // docs is List[DBObject]

Now, I'm seeing this error when trying to insert.

java.lang.IllegalArgumentException: BasicBSONList can only work with numeric keys, not: [_id]

EDIT

Full stack trace

[info]   java.lang.IllegalArgumentException: BasicBSONList can only work with numeric keys, not: [_id]
[info]   at org.bson.types.BasicBSONList._getInt(BasicBSONList.java:161)
[info]   at org.bson.types.BasicBSONList._getInt(BasicBSONList.java:152)
[info]   at org.bson.types.BasicBSONList.get(BasicBSONList.java:104)
[info]   at com.mongodb.DBCollection.apply(DBCollection.java:767)
[info]   at com.mongodb.DBCollection.apply(DBCollection.java:756)
[info]   at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:220)
[info]   at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:204)
[info]   at com.mongodb.DBCollection.insert(DBCollection.java:76)
[info]   at com.mongodb.casbah.MongoCollectionBase$class.insert(MongoCollection.scala:508)
[info]   at com.mongodb.casbah.MongoCollection.insert(MongoCollection.scala:866)

I've checked out a post with my exact same problem, but I'm not sure how to apply the accepted answer.

Does this error mean that I cannot insert any key-value pairs such that value is not castable to Int (per BasicBSONList)?


Solution

  • MongoDBList is not the same as an ordinary list, it is a convenience wrapper for BasicDBList and as such converting to vargs doesn't work as expected.

    You should supply List[DBObject] and then explode into vargs:

    val docs = List[DBObject("a" -> "b")
    collection.insert(docs: _*)