Oibríochtaí MongoDB CRUD le Python(Pymongo)

Is dáileadh Python é PyMongo ina bhfuil uirlisí le haghaidh oibriú le MongoDB, Mar sin sa phost blag seo feicfimid roinnt modhanna bunúsacha a dhéanann oibríochtaí CRUD chuig bailiúchán. insert_one(), insert_many(), find_one(), find(), update(), delete(), ...

Déanaim, Nasc agus Cruthaigh Bunachar Sonraí

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

II, Cruthaigh, Scríobh

1, cuir isteach()

is féidir é a úsáid chun 1 taifead nó níos mó a chur isteach.

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

cuir isteach() tuairisceáin mhodha

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

2, cuir isteach_amháin()

cuireann sé taifead amháin isteach i DB

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

3, cuir isteach_many()

cuireann sé taifead iolrach isteach i mbailiúchán

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

III, Nuashonrú

1, nuashonrú()

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

2, nuashonraigh_one()

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

3, nuashonraigh_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, Roghnaigh sonraí, Léigh, Faigh, Cuardach, Sórtáil

1, faigh()

cuireann sé gach taifead ar ais

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

2, aimsigh_amháin()

ar ais an chéad taifead

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

3, Scagaire

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

aimsigh gach taifead a dtosaíonn a ainm úsáideora le 'a'

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

4, Sórtáil

ASC

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

DESC

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

5, teorainn

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

V, Scrios

1, scrios_amháin()

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

2, scrios_go leor()

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