1

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.

1 Answer 1

1

$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}})
Sign up to request clarification or add additional context in comments.

1 Comment

I just realised I actually wanted typeA to be an array of objects. so using your answer I have realised i was looking for: from_collection.update({"ID":fromID},{"$addToSet":{'links.'+toType: to_link}}). though you have answered my question as it stood.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.