How can I create as below showing mongodb collocation using pymongo in mongodb python, and how insert new object only address array ?
{
_id: "joe",
name: "Joe Bookreader",
addresses: [
{
street: "123 Fake Street",
city: "Faketon",
state: "MA",
zip: "12345"
},
{
street: "1 Some Other Street",
city: "Boston",
state: "MA",
zip: "12345"
}
]
}
You need to use $push
if (_id_exists):
newAdrz = {"$push": {"addresses":
{
street: "1 Some Other Street",
city: "Boston",
state: "MA",
zip: "12345"
}}
}
self.collection.update({_id: "joe"}, newAdrz)
else:
root = {_id: "joe",name: "Joe Bookreader",
addresses: [
{
street: "123 Fake Street",
city: "Faketon",
state: "MA",
zip: "12345"
}]
}
self.collection.insert(root)
This will update the addresses array if _id already exists in the mongodb