Operazzjonijiet MongoDB CRUD b'Python(Pymongo)

PyMongo hija distribuzzjoni Python li fiha għodod biex taħdem ma 'MongoDB, Allura f'dan il-blog post ejja naraw xi metodi bażiċi li jwettqu operazzjonijiet CRUD għal kollezzjoni. insert_one(), insert_many(), find_one(), find(), update(), delete(),...

I, Ikkonnettja u Oħloq Database

import pymongo  
  
myclient = pymongo.MongoClient("mongodb://localhost:27017/")  
mydb = myclient["mydatabase"]  
mycol = mydb["mytable"]

II, Oħloq, Ikteb

1, daħħal()

jista' jintuża biex jiddaħħal rekord wieħed jew aktar.

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" }])

daħħal() jirritorna l-metodu

# insert single user  
ObjectId('5fbe1c17242098c02a7f4ecb')  
  
# insert many users  
[ObjectId('5fbe1c17242098c02a7f4ecb'), ObjectId('5fbe1c63fa9741631f6a1f6c')]

2, daħħal_wieħed()

idaħħal rekord wieħed f'DB

mycol.insert_one({ "username": "aaa", "pass": "123456" })

3, daħħal_ħafna()

idaħħal rekord multiplu f'kollezzjoni

mycol.insert_many([  
    { "username": "aaa", "pass": "123456" },  
    { "username": "bbb", "pass": "123456" },  
    { "username": "ccc", "pass": "123456" }  
])

III, Aġġornament

1, aġġornament()

myquery = { "username": "aaa" }  
newvalues = { "$set": { "username": "ddd" } }  
  
mycol.update(myquery, newvalues)

2, update_one()

myquery = { "username": "aaa" }  
newvalues = { "$set": { "username": "ddd" } }  
  
mycol.update_one(myquery, newvalues)

3, update_many()

myquery = { "username": "aaa" }  
newvalues = { "$set": { "username": "ddd" } }  
  
mycol.update_many(myquery, newvalues)

4, replace_one()

myquery = { "username": "aaa" }  
newvalues = { "username": "ddd" }  
  
mycol.replace_one(myquery, newvalues)

IV, Agħżel data, Aqra, Sib, Fittex, Sort

1, issib()

jirritorna r-rekords kollha

mycol.find()  
# return  
<pymongo.cursor.Cursor object at 0x7f8fc1878890>

2, find_one()

lura l-ewwel rekord

mycol.find_one()  
  
# return   
{'id': ObjectId('5fbe1c17242098c02a7f4ecb'), 'username': 'aaa',  'pass': '123456'}

3, Iffiltra

myquery = { "username": "aaa" }   
mydoc = mycol.find(myquery)  
  
for x in mydoc:  
  print(x)

sib ir-rekords kollha li l-isem tal-utent tagħhom jibda b''a'

myquery = { "username": { "$gt": "a" } }  
mydoc = mycol.find(myquery)  
  
for x in mydoc:  
  print(x)

4, Sort

ASC

mydoc = mycol.find().sort("username", 1)

DESC

mydoc = mycol.find().sort("username", -1)

5, limitu

users = mycol.find().limit(5)

V, Ħassar

1, delete_one()

mycol.delete_one({ "username": "aaa" })

2, ħassar_ħafna()

mycol.delete_many({ "username": "aaa" })