Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

pymongo - How I can udate a document in mongodb without delete the information it contains?

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" : "[email protected]",
    "user_ip" : "127.0.0.1",
    "timestamp_id" : ISODate("2021-02-05T08:56:32.432Z")
},
"subprofile" : {
    "email" : "[email protected]",
    "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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...