PyMongo ni usambazaji wa Python ambao una zana za kufanya kazi na MongoDB, Kwa hivyo katika chapisho hili la blogi wacha tuone njia kadhaa za kimsingi ambazo hufanya shughuli za CRUD kwa mkusanyiko. insert_one(), insert_nyingi(), find_one(), find(), update(), delete(), ...
Mimi, Unganisha na Unda Hifadhidata
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["mytable"]
II, Unda, Andika
1, weka()
inaweza kutumika kuingiza rekodi 1 au zaidi.
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["users"]
# insert single user
mycol.insert({ "username": "aaa", "pass": "123456" })
# insert many users
mycol.insert([{ "username": "bbb", "pass": "123456" }, { "username": "ccc", "pass": "123456" }])
insert() njia inarudi
# insert single user
ObjectId('5fbe1c17242098c02a7f4ecb')
# insert many users
[ObjectId('5fbe1c17242098c02a7f4ecb'), ObjectId('5fbe1c63fa9741631f6a1f6c')]
2, ingiza_moja()
inaingiza rekodi moja kwenye DB
mycol.insert_one({ "username": "aaa", "pass": "123456" })
3, ingiza_nyingi()
huingiza rekodi nyingi kwenye mkusanyiko
mycol.insert_many([
{ "username": "aaa", "pass": "123456" },
{ "username": "bbb", "pass": "123456" },
{ "username": "ccc", "pass": "123456" }
])
III, Sasisho
1, sasisha()
myquery = { "username": "aaa" }
newvalues = { "$set": { "username": "ddd" } }
mycol.update(myquery, newvalues)
2, sasisha_moja()
myquery = { "username": "aaa" }
newvalues = { "$set": { "username": "ddd" } }
mycol.update_one(myquery, newvalues)
3, sasisha_nyingi()
myquery = { "username": "aaa" }
newvalues = { "$set": { "username": "ddd" } }
mycol.update_many(myquery, newvalues)
4, badilisha_moja()
myquery = { "username": "aaa" }
newvalues = { "username": "ddd" }
mycol.replace_one(myquery, newvalues)
IV, Chagua data, Soma, Tafuta, Tafuta, Panga
1, kupata()
inarudisha rekodi zote
mycol.find()
# return
<pymongo.cursor.Cursor object at 0x7f8fc1878890>
2, pata_moja()
rudisha rekodi ya kwanza
mycol.find_one()
# return
{'id': ObjectId('5fbe1c17242098c02a7f4ecb'), 'username': 'aaa', 'pass': '123456'}
3, Kichujio
myquery = { "username": "aaa" }
mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
pata rekodi zote ambazo jina la mtumiaji linaanza na 'a'
myquery = { "username": { "$gt": "a" } }
mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
4, Panga
ASC
mydoc = mycol.find().sort("username", 1)
DESC
mydoc = mycol.find().sort("username", -1)
5, kikomo
users = mycol.find().limit(5)
V, Futa
1, kufuta_moja()
mycol.delete_one({ "username": "aaa" })
2, delete_nyingi()
mycol.delete_many({ "username": "aaa" })