Saving pymongo inline objects, InvalidDocumentError

Using the pymongo driver to connect python to mongodb, why does it use an ObjectId instance as a key for an inline document that causes an InvalidDocument error?

I am trying to link documents using objectids and cannot understand why I would like to convert them to strings when those automatically created for the driver are instances ObjectId.

item = collection.find({'x':'foo'})
item['otherstuff'] = {pymongo.objectid.ObjectId() : 'data about this link'}
collection.update({'x':'foo'}, item)
bson.errors.InvalidDocument: documents must have only string keys, key was ObjectId('4f0b5d4e764df61c67000000')

In practice, related identifiers are documents containing questions, and the values ​​in the dictionary, which are called “others,” for example, are separate answers to this particular question.

Is there a reason why the use of such objects will not be encoded in bson, and then will not be executed? Is it impossible to cross-reference nested documents in such documents in Objective files? Did I misunderstand their purpose?

+1
source share
1 answer

The BSON specification states that keys must be strings, so PyMongo is right to reject this as an invalid document (and it will be regardless of what level of ObjectId was used as the key, whether at the top level or in the embedded document). This is necessary, among other reasons, so the query language can be unambiguous. Imagine that you have this document (and that it was a valid BSON document):

{ _id: ...,
  "4f0cbe6d7f40d36b24a5c4d7":           true,
  ObjectId("4f0cbe6d7f40d36b24a5c4d7"): false
}

:

db.foo.find({"4f0cbe6d7f40d36b24a5c4d7": false})

? ObjectId? Mongo, , , ?

- , :

{ answers: [
    { answer_id: ObjectId("..."), summary: "Good answer to this question" },
    { answer_id: ObjectId("..."), summary: "Bad answer to this question" }
  ]
}

BSON, . answers, ; answers.answer_id, ObjectId , ( ..).

+6

Source: https://habr.com/ru/post/1525536/


All Articles