I am writing a program in Django using pymongo and I am using MongoDB database.
I have the following document:
{
"_id" : ObjectId("601cfa306f67d4f34bee6873"),
"user_id" : 2,
"timestamp" : ISODate("2021-02-05T08:56:32.432Z"),
"ips" : {
"email" : "user1@gmail.com",
"user_ip" : "127.0.0.1",
"timestamp_id" : ISODate("2021-02-05T08:56:32.432Z")
},
"subprofile" : {
"email" : "permission@gmail.com",
"permission" : "post messages",
"timestamp" : ISODate("2021-02-05T09:49:26.949Z")
}}
I want to update "subprofile" with the following code
def mongodb(id, email, permission):
mongo = MongoClient(port=27017)
db = mongo['engine']
collection = db['app_profile']
user = collection.find({'user_id': id})
#takes the _id and subpfofile
for u in user:
user_id = u.get('_id')
is_first= u.get('subprofile')
#checks if it is the first time that you use the databese
if len(is_first) == 0:
#use the function write_permission to update the information for the first time
collection.update({'_id': user_id}, {'$set':{'subprofile': write_permission(email, permission)}},
upsert=True)
#if subprofile contains some information add with write_permission other information without override
the others
else:
collection.update({'_id': user_id},{'$set':{'subprofile':write_permission(email, permission)})
def write_permission(email, permission):
post = {
"email": email,
"permission": permission,
"timestamp": datetime.datetime.now(),
}
return post
However, with $set
I override the previous information!
I do not have a clue how to 'update' and do not override subprofile. If it would an array I would use $puch, but this is not the cases.
Any help will be appreciated, thanks.
question from:
https://stackoverflow.com/questions/66060664/how-i-can-udate-a-document-in-mongodb-without-delete-the-information-it-contains 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…