问题
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