How to do Mongo inserts?

Asked

Viewed 94 times

2

I’m doing a program that will perform numerous insertions in Mongo (about 500,000). But I noticed doing some tests, that the more entries in Mongo I have, the longer is the insertion.

My code:

def savePostRecommendation(uid, recs, db):
    temp = db.posts.find_one({'uid':uid})
    if(temp is None):
        db.posts.insert({'uid':uid,'recs':recs})
    else:
        db.posts.update({'uid':uid},{'uid':uid,'recs':recs})

My theory:

I’m making an inquiry to see if there’s an entry temp = db.posts.find_one({'uid':uid}), because if the function was only db.posts.Insert({'uid':uid,'Recs':Recs}), if the code was executed again there would be two entries in the Mongo with the same values. So I think when more entries in the Mongo I own this search that I do takes longer and longer.

My question is: How do I insert a value defining my attribute uid as a primary key like SQL does. So then I insert the input without checking if it exists and that there is no uids duplicates?

1 answer

2


Mongodb does not have a type of auto-increment as in SQL databases, but _id is something very special to him. What you can do is indicate which is the _id manually:

db.posts.save({'_id':uid,'recs':recs});

Important to note that this value is always unique (if it is omitted, mongoDB will create the hash standard). You can save if else using the expression save which will create a new or update if identifier already exists.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.