MongoDB CRUD yana aiki tare da Python(Pymongo)

PyMongo shine rarraba Python wanda ya ƙunshi kayan aikin aiki tare da MongoDB, Don haka a cikin wannan gidan yanar gizon bari mu ga wasu mahimman hanyoyin da ke aiwatar da ayyukan CRUD zuwa tarin. saka_one(), saka_yawan(), find_one(), nemo(), sabunta(), share(), ...

I, Haɗa da Ƙirƙiri Database

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

II, Ƙirƙiri, Rubuta

1, saka()

za a iya amfani dashi don saka bayanai 1 ko fiye.

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

saka() hanyar dawowa

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

2, saka_daya()

yana saka rikodin guda ɗaya a cikin DB

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

3, saka_yawa()

yana shigar da rikodi da yawa cikin tarin

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

III, Sabuntawa

1, sabunta()

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

2, sabunta_daya()

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

3, sabunta_yawan()

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

4, maye gurbin_daya()

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

IV, Zaɓi bayanai, Karanta, Nemo, Bincika, Tsara

1, samu()

dawo da duk bayanan

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

2, sami_daya()

mayar da rikodin farko

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

3, Tace

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

nemo duk bayanan da sunan mai amfani ya fara da 'a'

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

4 ,Kasuwa

ASC

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

DESC

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

5, iyaka

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

V, Share

1, share_daya()

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

2, share_da yawa()

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