I just start learning mongodb, and don’t know a lot yet.
so my code:
#! /usr/bin/env python2.7
import pymongo
import datetime
class AccountsDB():
def __init__(self):
self.store_info()
def store_info(self):
try:
conn = pymongo.Connection('localhost', 27017)
db_name = 'accountsdb'
coll_name = 'user_info'
db = conn[db_name]
coll = db[coll_name]
print "Successfully connected to '%s'" % db_name
for i in xrange(20):
post = {
'f_name' : 'Sergey',
'l_name' : 'Ivanov',
'number' : '777-9-777',
'user_id': i
}
coll.insert(post)
print "Done"
except:
print "Can't connect to the database"
if __name__ == "__main__":
acc = AccountsDB()
and it gives me :
> db.user_info.find()
{ "_id" : ObjectId("50c64872bdbff34435192a94"), "l_name" : "Ivanov", "f_name" : "Sergey", "user_id" : 0, "number" : "777-9-777" }
{ "_id" : ObjectId("50c64872bdbff34435192a95"), "l_name" : "Ivanov", "f_name" : "Sergey", "user_id" : 1, "number" : "777-9-777" }
{ "_id" : ObjectId("50c64872bdbff34435192a96"), "l_name" : "Ivanov", "f_name" : "Sergey", "user_id" : 2, "number" : "777-9-777" }
{ "_id" : ObjectId("50c64872bdbff34435192a97"), "l_name" : "Ivanov", "f_name" : "Sergey", "user_id" : 3, "number" : "777-9-777" }
{ "_id" : ObjectId("50c64872bdbff34435192a98"), "l_name" : "Ivanov", "f_name" : "Sergey", "user_id" : 4, "number" : "777-9-777" }
{ "_id" : ObjectId("50c64872bdbff34435192a99"), "l_name" : "Ivanov", "f_name" : "Sergey", "user_id" : 5, "number" : "777-9-777" }
and so on....
But I want to get rid of ‘_id’ and use ‘user_id’ instead as my primary key. I’m pretty sure it can be done, but don’t know how.
I am pretty sure that the answer is no, you cant disable “_id”. why?
just take a look to the source code of pymongo. Take a look to collection.py and search for “_id”.
Mmm I think this could be done via monkey patching, but its to dark magic. just an idea and I dont recommend monkey patching at all. thats why my answer is no 🙁