Insertions in mongo how to do?

2

I'm doing a program that will hold numerous inserts in the mongo (about 500,000). But I realized by doing some tests, that the more entries in the mongo I have, the more time consuming 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 am making a query to check if the temp = db.posts.find_one({'uid':uid}) entry exists, because if the function was just db.posts.insert ({'uid': uid, 'recs': recs}), if the code was run again there would be two entries in the mongo with the same values. So I guess when I get more entries in the mongo I have this search that I take more and more time.

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

    
asked by anonymous 26.02.2018 / 20:11

1 answer

2

MongoDB does not have an auto-increment type like in SQL databases, but _id is something very special to it. What you can do is to indicate what _id is 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 default ). You can save if else by using the expression save that will create a new one or update if identifier already exists.

    
06.03.2018 / 15:41