Search code examples
pythonmongodbpymongo

How to insert an embedded object with dot notations in MongoDB


For example, you can use dot notations while changing the contents of a object:

collection.update_one({"_id": 123456}, {"$set": {"abc.def.ghi": 123}})

Which is great but, i cant use it to create new documents, when i do:

collection.insert_one({"_id": 123456, "abc.def.ghi": 123}) 

To create a new document, it just inserts a document like this:

{
    "_id": 123456,
    "abc.def.ghi": 123
}

While i want it to insert a document like this:

{
    "_id": 123456,
    "abc": {
        "def": {
            "ghi": 123
        }
    }
}

Solution

  • You can't use dot notation in that way on an insert_one(). Just use:

    collection.insert_one({"_id": 123456, "abc": {"def": {"ghi": 123}}})