Operasi CRUD MongoDB nganggo Python(Pymongo)

PyMongo minangka distribusi Python sing ngemot alat kanggo nggarap MongoDB, Dadi ing kirim blog iki ayo ndeleng sawetara cara dhasar sing nindakake operasi CRUD menyang koleksi. insert_one(), insert_many(), find_one(), golek(), update(), delete(),...

Aku, Sambungake lan Nggawe Database

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

II, Nggawe, Nulis

1, insert()

bisa digunakake kanggo masang 1 utawa luwih cathetan.

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

cara insert() ngasilake

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

2, insert_one()

nglebokake rekaman siji menyang DB

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

3, insert_many()

nglebokake sawetara rekaman menyang koleksi

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

III, Nganyari

1, nganyari()

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, ganti_siji()

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

IV, Pilih data, Waca, Golek, Telusuri, Urut

1, golek()

ngasilake kabeh cathetan

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

2, golek_siji()

bali rekor pisanan

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

3, Saringan

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

temokake kabeh cathetan sing jeneng pangguna diwiwiti kanthi 'a'

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

4, Urut

ASC

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

DESC

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

5, watesan

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

V, Mbusak

1, delete_one()

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

2, delete_many()

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