johowie
johowie

Reputation: 2495

$addToSet nested nested object using pymongo

As part of a for-in loop in python using pymongo I want to add some nested documents/objects inside a linktype field which is to be within a links field: neither the links field or linktype field exists before the first such entries are to be added.

What is the commands to do this ?

Here is an item before adding links:

item = {
    "_id" : ObjectId("5067c26b9d595266e25e825a"),
    "name": "a Name"
}

And after adding one link of type typeA:

toType = "typeA"
to_link = {"_id" : ObjectId("5067c26b9d595266e25e825b"), "property":"value"}

{
    "_id" : ObjectId("5067c26b9d595266e25e825a"),
    "name": "a Name",
    "links" : {
        "typeA":{
            {"_id" : ObjectId("5067c26b9d595266e25e825b"), "property":"value"}       
        }
    }
}

I have tried:

db.collection.update({"name":"a Name"},{{"links":{"$addToSet":{toType:to_link}}})

which doesnt work. If I just use:

db.collection.update({"name":"a Name"},{ {"$addToSet":{toType:to_link}} )

that works but that is not what i want.

Upvotes: 1

Views: 1901

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

$addToSet is for adding to an array. To add a new property to an existing embedded object you need to use the $set operator and dot notation as:

db.collection.update({name: 'a name'}, {$set: {'links.' + toType: to_link}})

Upvotes: 1

Related Questions