error when creating object in collection in mongolab: BasicBSONList can only work with numeric keys, not: [_id]

元气小坏坏 提交于 2020-01-06 02:26:07

问题


I'm using the following JSON (and have validated it) for my collection in MongoLab:

[{
    "city": "ACMAR",
    "pop": 6055,
    "state": "AL",
    "_id": "35004"
},
{
    "city": "ADAMSVILLE",
    "pop": 10616,
    "state": "AL",
    "_id": "35005"
},
{
    "city": "ADGER",
    "pop": 3205,
    "state": "AL",
    "_id": "35006"
}]

But I keep getting this error: BasicBSONList can only work with numeric keys, not: [_id]. So what am I doing wrong?


回答1:


I think I may have an idea of what the problem is, but can you elaborate on a few things? Is this a list of documents from your collection or a list that is included in a larger document? Where you are getting the error exactly?

The MongoLab document editor only takes one document ({} not []), it doesn't support batch inserts at this time.

If you're having this problem in code, then by making a few assumptions, I can speculate that if the JSON provided is "data" then:

data is a BasicBSONList (or BasicDBList), which cannot be accessed by calling .get("somefieldname"). Instead, either:

a) iterate over the elements of the list to access them:

for(BasicDBObject doc : data) { String id = (String) doc.get("_id"); }

b) use a known list index as an intermediary

String _id = (String) ((DBObject)data.get(1)).get("_id"); //or
String _id = (String) ((DBObject)data.get("1")).get("_id");

This is because, under-the-hood, a BSONList looks something like:

{
"0": {
    "city": "ACMAR",
    "pop": 6055,
    "state": "AL",
    "_id": "35004"
},
"1": {
    "city": "ADAMSVILLE",
    "pop": 10616,
    "state": "AL",
    "_id": "35005"
},
"2": {
    "city": "ADGER",
    "pop": 3205,
    "state": "AL",
    "_id": "35006"
}
}

Let me know if this helps!

Gratefully, Eric@MongoLab



来源:https://stackoverflow.com/questions/16611255/error-when-creating-object-in-collection-in-mongolab-basicbsonlist-can-only-wor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!