Python MongoDB - szybki przewodnik
Pymongo to dystrybucja Pythona dostarczająca narzędzi do pracy z MongoDB, jest to najbardziej preferowany sposób komunikacji z bazą danych MongoDB z poziomu pythona.
Instalacja
Aby zainstalować pymongo, przede wszystkim upewnij się, że poprawnie zainstalowałeś python3 (wraz z PIP) i MongoDB. Następnie wykonaj następujące polecenie.
C:\WINDOWS\system32>pip install pymongo
Collecting pymongo
Using cached https://files.pythonhosted.org/packages/cb/a6/b0ae3781b0ad75825e00e29dc5489b53512625e02328d73556e1ecdf12f8/pymongo-3.9.0-cp37-cp37m-win32.whl
Installing collected packages: pymongo
Successfully installed pymongo-3.9.0
Weryfikacja
Po zainstalowaniu pymongo otwórz nowy dokument tekstowy, wklej w nim następującą linię i zapisz jako test.py.
import pymongo
Jeśli poprawnie zainstalowałeś pymongo, jeśli uruchomisz plik test.py, jak pokazano poniżej, nie powinieneś mieć żadnych problemów.
D:\Python_MongoDB>test.py
D:\Python_MongoDB>
W przeciwieństwie do innych baz danych, MongoDB nie zapewnia oddzielnego polecenia do tworzenia bazy danych.
Ogólnie polecenie use służy do wybierania / przełączania się do określonej bazy danych. To polecenie wstępnie sprawdza, czy wskazana przez nas baza danych istnieje, jeśli tak, łączy się z nią. Jeśli baza danych, którą określimy poleceniem use, nie istnieje, zostanie utworzona nowa baza danych.
W związku z tym można utworzyć bazę danych w MongoDB przy użyciu Use Komenda.
Składnia
Podstawowa składnia use DATABASE oświadczenie jest następujące -
use DATABASE_NAME
Przykład
Następujące polecenie tworzy bazę danych o nazwie w mydb.
>use mydb
switched to db mydb
Możesz zweryfikować swoje tworzenie za pomocą komendy db , która wyświetli aktualną bazę danych.
>db
mydb
Tworzenie bazy danych w języku Python
Aby połączyć się z MongoDB za pomocą pymongo, musisz zaimportować i utworzyć MongoClient, a następnie możesz uzyskać bezpośredni dostęp do bazy danych, którą musisz utworzyć w pasji atrybutów.
Przykład
Poniższy przykład tworzy bazę danych w MangoDB.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['mydb']
print("Database created........")
#Verification
print("List of databases after creating new one")
print(client.list_database_names())
Wynik
Database created........
List of databases after creating new one:
['admin', 'config', 'local', 'mydb']
Możesz również określić port i nazwy hostów podczas tworzenia MongoClient i uzyskać dostęp do baz danych w stylu słownikowym.
Przykład
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['mydb']
print("Database created........")
Wynik
Database created........
Kolekcja w MongoDB zawiera zestaw dokumentów, jest analogiczna do tabeli w relacyjnych bazach danych.
Możesz utworzyć kolekcję za pomocą createCollection()metoda. Ta metoda akceptuje wartość String reprezentującą nazwę kolekcji do utworzenia i parametr options (opcjonalny).
Za pomocą tego możesz określić następujące elementy -
Wielkość zbiorów.
Max liczba dokumentów dopuszczonych w zakorkowanej kolekcji.
Czy tworzona przez nas kolekcja powinna być kolekcją zamkniętą (zbiór o stałym rozmiarze).
Czy tworzona przez nas kolekcja powinna być indeksowana automatycznie.
Składnia
Poniżej przedstawiono składnię tworzenia kolekcji w MongoDB.
db.createCollection("CollectionName")
Przykład
Poniższa metoda tworzy kolekcję o nazwie ExampleCollection.
> use mydb
switched to db mydb
> db.createCollection("ExampleCollection")
{ "ok" : 1 }
>
Podobnie, następujące zapytanie tworzy kolekcję przy użyciu opcji metody createCollection ().
>db.createCollection("mycol", { capped : true, autoIndexId : true, size :
6142800, max : 10000 } )
{ "ok" : 1 }
>
Tworzenie kolekcji za pomocą Pythona
Poniższy przykład w Pythonie łączy się z bazą danych w MongoDB (mydb) i tworzy w niej kolekcję.
Przykład
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['mydb']
#Creating a collection
collection = db['example']
print("Collection created........")
Wynik
Collection created........
Możesz przechowywać dokumenty w MongoDB za pomocą metody insert () . Ta metoda akceptuje dokument JSON jako parametr.
Składnia
Poniżej przedstawiono składnię metody insert.
>db.COLLECTION_NAME.insert(DOCUMENT_NAME)
Przykład
> use mydb
switched to db mydb
> db.createCollection("sample")
{ "ok" : 1 }
> doc1 = {"name": "Ram", "age": "26", "city": "Hyderabad"}
{ "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
> db.sample.insert(doc1)
WriteResult({ "nInserted" : 1 })
>
Podobnie możesz również wstawić wiele dokumentów za pomocą rozszerzenia insert() metoda.
> use testDB
switched to db testDB
> db.createCollection("sample")
{ "ok" : 1 }
> data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" },
{"_id": "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
]
[
{"_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad"},
{"_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore"},
{"_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai"}
]
> db.sample.insert(data)
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
>
Tworzenie kolekcji za pomocą Pythona
Pymongo udostępnia metodę o nazwie insert_one () do wstawiania dokumentu do MangoDB. Do tej metody musimy przekazać dokument w formacie słownikowym.
Przykład
Poniższy przykład wstawia dokument do kolekcji o nazwie example.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['mydb']
#Creating a collection
coll = db['example']
#Inserting document into a collection
doc1 = {"name": "Ram", "age": "26", "city": "Hyderabad"}
coll.insert_one(doc1)
print(coll.find_one())
Wynik
{'_id': ObjectId('5d63ad6ce043e2a93885858b'), 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
Aby wstawić wiele dokumentów do MongoDB za pomocą pymongo, musisz wywołać metodę insert_many ().
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['mydb']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
print(res.inserted_ids)
Wynik
Data inserted ......
['101', '102', '103']
Możesz czytać / pobierać zapisane dokumenty z MongoDB przy użyciu rozszerzenia find()metoda. Ta metoda pobiera i wyświetla wszystkie dokumenty w MongoDB w sposób bez struktury.
Składnia
Poniżej znajduje się składnia find() metoda.
>db.COLLECTION_NAME.find()
Przykład
Załóżmy, że wstawiliśmy 3 dokumenty do bazy danych o nazwie testDB w kolekcji o nazwie sample, używając następujących zapytań -
> use testDB
> db.createCollection("sample")
> data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" },
{"_id": "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
]
> db.sample.insert(data)
Możesz pobrać wstawione dokumenty za pomocą metody find () jako -
> use testDB
switched to db testDB
> db.sample.find()
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
>
Możesz również pobrać pierwszy dokument w kolekcji za pomocą metody findOne () jako -
> db.sample.findOne()
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
Pobieranie danych (znajdowanie) za pomocą języka Python
Plik find_One() metoda pymongo służy do pobrania pojedynczego dokumentu na podstawie zapytania, w przypadku braku dopasowań metoda ta nic nie zwraca, a jeśli nie używasz żadnego zapytania, zwraca pierwszy dokument z kolekcji.
Ta metoda jest przydatna, gdy potrzebujesz pobrać tylko jeden dokument wyniku lub jeśli masz pewność, że zapytanie zwraca tylko jeden dokument.
Przykład
Poniższy przykład w języku Python umożliwia pobranie pierwszego dokumentu z kolekcji -
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['mydatabase']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
print(res.inserted_ids)
#Retrieving the first record using the find_one() method
print("First record of the collection: ")
print(coll.find_one())
#Retrieving a record with is 103 using the find_one() method
print("Record whose id is 103: ")
print(coll.find_one({"_id": "103"}))
Wynik
Data inserted ......
['101', '102', '103']
First record of the collection:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
Record whose id is 103:
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Aby uzyskać wiele dokumentów w jednym zapytaniu (pojedyncze wywołanie metody find), możesz użyć rozszerzenia find()metoda pymongo. Jeśli żadne zapytanie nie przeszło, zwraca wszystkie dokumenty kolekcji, a jeśli przekazałeś zapytanie do tej metody, zwraca wszystkie dopasowane dokumenty.
Przykład
#Getting the database instance
db = client['myDB']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving all the records using the find() method
print("Records of the collection: ")
for doc1 in coll.find():
print(doc1)
#Retrieving records with age greater than 26 using the find() method
print("Record whose age is more than 26: ")
for doc2 in coll.find({"age":{"$gt":"26"}}):
print(doc2)
Wynik
Data inserted ......
Records of the collection:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Record whose age is more than 26:
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Podczas pobierania za pomocą find()możesz filtrować dokumenty za pomocą obiektu zapytania. Możesz przekazać kwerendę określającą warunek wymaganych dokumentów jako parametr do tej metody.
Operatorzy
Poniżej znajduje się lista operatorów używanych w zapytaniach w MongoDB.
Operacja | Składnia | Przykład |
---|---|---|
Równość | {"kluczowa wartość"} | db.mycol.find ({"by": "punkt samouczka"}) |
Mniej niż | {"klucz": {$ lt: "wartość"}} | db.mycol.find ({"lubi": {$ lt: 50}}) |
Mniej niż równa się | {"klucz": {$ lte: "wartość"}} | db.mycol.find ({"lubi": {$ lte: 50}}) |
Lepszy niż | {"klucz": {$ gt: "wartość"}} | db.mycol.find ({"lubi": {$ gt: 50}}) |
Większe niż równe | {"klucz" {$ gte: "wartość"}} | db.mycol.find ({"lubi": {$ gte: 50}}) |
Nie równa się | {"klucz": {$ ne: "wartość"}} | db.mycol.find ({"lubi": {$ ne: 50}}) |
Przykład 1
Poniższy przykład pobiera dokument w kolekcji o nazwie sarmista.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['sdsegf']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
{"_id": "1004", "name": "Romeo", "age": "25", "city": "Pune"},
{"_id": "1005", "name": "Sarmista", "age": "23", "city": "Delhi"},
{"_id": "1006", "name": "Rasajna", "age": "26", "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving data
print("Documents in the collection: ")
for doc1 in coll.find({"name":"Sarmista"}):
print(doc1)
Wynik
Data inserted ......
Documents in the collection:
{'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'}
Przykład 2
Poniższy przykład pobiera dokument w kolekcji, której wartość wieku jest większa niż 26.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['ghhj']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
{"_id": "1004", "name": "Romeo", "age": "25", "city": "Pune"},
{"_id": "1005", "name": "Sarmista", "age": "23", "city": "Delhi"},
{"_id": "1006", "name": "Rasajna", "age": "26", "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving data
print("Documents in the collection: ")
for doc in coll.find({"age":{"$gt":"26"}}):
print(doc)
Wynik
Data inserted ......
Documents in the collection:
{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Podczas pobierania zawartości kolekcji można sortować i porządkować je w kolejności rosnącej lub malejącej przy użyciu rozszerzenia sort() metoda.
Do tej metody możesz przekazać pole (a) i kolejność sortowania, która wynosi 1 lub -1. Gdzie 1 oznacza kolejność rosnącą, a -1 malejącą.
Składnia
Poniżej znajduje się składnia metody sort () .
>db.COLLECTION_NAME.find().sort({KEY:1})
Przykład
Załóżmy, że utworzyliśmy kolekcję i wstawiliśmy do niej 5 dokumentów, jak pokazano poniżej -
> use testDB
switched to db testDB
> db.createCollection("myColl")
{ "ok" : 1 }
> data = [
... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
... {"_id": "1002", "name": "Rahim", "age": 27, "city": "Bangalore"},
... {"_id": "1003", "name": "Robert", "age": 28, "city": "Mumbai"},
... {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"},
... {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"},
... {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"}
]
> db.sample.insert(data)
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 6,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
Następna linia pobiera wszystkie dokumenty kolekcji, które są posortowane rosnąco na podstawie wieku.
> db.sample.find().sort({age:1})
{ "_id" : "1005", "name" : "Sarmista", "age" : 23, "city" : "Delhi" }
{ "_id" : "1004", "name" : "Romeo", "age" : 25, "city" : "Pune" }
{ "_id" : "1006", "name" : "Rasajna", "age" : 26, "city" : "Chennai" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
Sortowanie dokumentów za pomocą Pythona
Aby posortować wyniki zapytania w porządku rosnącym lub malejącym, pymongo udostępnia rozszerzenie sort()metoda. Do tej metody należy przekazać wartość liczbową reprezentującą liczbę dokumentów potrzebnych w wyniku.
Domyślnie ta metoda sortuje dokumenty w kolejności rosnącej na podstawie określonego pola. Jeśli chcesz posortować w porządku malejącym pass -1 wraz z nazwą pola -
coll.find().sort("age",-1)
Przykład
Poniższy przykład pobiera wszystkie dokumenty kolekcji uporządkowane według wartości wieku w porządku rosnącym -
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['b_mydb']
#Creating a collection
coll = db['myColl']
#Inserting document into a collection
data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
{"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"},
{"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"},
{"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving first 3 documents using the find() and limit() methods
print("List of documents (sorted in ascending order based on age): ")
for doc1 in coll.find().sort("age"):
print(doc1)
Wynik
Data inserted ......
List of documents (sorted in ascending order based on age):
{'_id': '1005', 'name': 'Sarmista', 'age': 23, 'city': 'Delhi'}
{'_id': '1004', 'name': 'Romeo', 'age': 25, 'city': 'Pune'}
{'_id': '1006', 'name': 'Rasajna', 'age': 26, 'city': 'Chennai'}
{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Możesz usuwać dokumenty w kolekcji za pomocą remove()metoda MongoDB. Ta metoda akceptuje dwa opcjonalne parametry -
Kryteria usuwania określające warunek usunięcia dokumentów.
Tylko jeden, jeśli jako drugi parametr podasz wartość true lub 1, tylko jeden dokument zostanie usunięty.
Składnia
Poniżej znajduje się składnia metody remove () -
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Przykład
Załóżmy, że utworzyliśmy kolekcję i wstawiliśmy do niej 5 dokumentów, jak pokazano poniżej -
> use testDB
switched to db testDB
> db.createCollection("myColl")
{ "ok" : 1 }
> data = [
... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
... {"_id": "1002", "name": "Rahim", "age": 27, "city": "Bangalore"},
... {"_id": "1003", "name": "Robert", "age": 28, "city": "Mumbai"},
... {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"},
... {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"},
... {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"}
]
> db.sample.insert(data)
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 6,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
Poniższe zapytanie usuwa dokument (y) kolekcji, które mają wartość nazwy Sarmista.
> db.sample.remove({"name": "Sarmista"})
WriteResult({ "nRemoved" : 1 })
> db.sample.find()
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
{ "_id" : "1004", "name" : "Romeo", "age" : 25, "city" : "Pune" }
{ "_id" : "1006", "name" : "Rasajna", "age" : 26, "city" : "Chennai" }
Jeśli wywołasz remove() bez przejścia kryteriów usuwania, wszystkie dokumenty w kolekcji zostaną usunięte.
> db.sample.remove({})
WriteResult({ "nRemoved" : 5 })
> db.sample.find()
Usuwanie dokumentów za pomocą Pythona
Aby usunąć dokumenty z kolekcji MangoDB, możesz usunąć dokumenty z kolekcji przy użyciu tych metod delete_one() i delete_many() metody.
Te metody akceptują obiekt zapytania określający warunek usunięcia dokumentów.
Metoda detele_one () usuwa pojedynczy dokument w przypadku dopasowania. Jeśli nie określono zapytania, ta metoda usuwa pierwszy dokument w kolekcji.
Przykład
Poniższy przykład w Pythonie usuwa dokument w kolekcji, który ma wartość identyfikatora 1006.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['lpaksgf']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
{"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"},
{"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"},
{"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Deleting one document
coll.delete_one({"_id" : "1006"})
#Retrieving all the records using the find() method
print("Documents in the collection after update operation: ")
for doc2 in coll.find():
print(doc2)
Wynik
Data inserted ......
Documents in the collection after update operation:
{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
{'_id': '1004', 'name': 'Romeo', 'age': 25, 'city': 'Pune'}
{'_id': '1005', 'name': 'Sarmista', 'age': 23, 'city': 'Delhi'}
Podobnie delete_many() metoda pymongo usuwa wszystkie dokumenty spełniające podany warunek.
Przykład
Poniższy przykład usuwa wszystkie dokumenty w kolekcji, których wiek jest większy niż 26 -
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['sampleDB']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
{"_id": "1004", "name": "Romeo", "age": "25", "city": "Pune"},
{"_id": "1005", "name": "Sarmista", "age": "23", "city": "Delhi"},
{"_id": "1006", "name": "Rasajna", "age": "26", "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Deleting multiple documents
coll.delete_many({"age":{"$gt":"26"}})
#Retrieving all the records using the find() method
print("Documents in the collection after update operation: ")
for doc2 in coll.find():
print(doc2)
Wynik
Data inserted ......
Documents in the collection after update operation:
{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '1004', 'name': 'Romeo', 'age': '25', 'city': 'Pune'}
{'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'}
{'_id': '1006', 'name': 'Rasajna', 'age': '26', 'city': 'Chennai'}
Jeśli wywołasz metodę delete_many () bez przekazywania żadnego zapytania, ta metoda usunie wszystkie dokumenty w kolekcji.
coll.delete_many({})
Możesz usuwać kolekcje za pomocą drop() metoda MongoDB.
Składnia
Poniżej znajduje się składnia metody drop () -
db.COLLECTION_NAME.drop()
Przykład
Poniższy przykład porzuca kolekcję z próbką nazwy -
> show collections
myColl
sample
> db.sample.drop()
true
> show collections
myColl
Usuwanie kolekcji za pomocą Pythona
Możesz upuścić / usunąć kolekcję z bieżącej, wywołując metodę drop ().
Przykład
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['example2']
#Creating a collection
col1 = db['collection']
col1.insert_one({"name": "Ram", "age": "26", "city": "Hyderabad"})
col2 = db['coll']
col2.insert_one({"name": "Rahim", "age": "27", "city": "Bangalore"})
col3 = db['myColl']
col3.insert_one({"name": "Robert", "age": "28", "city": "Mumbai"})
col4 = db['data']
col4.insert_one({"name": "Romeo", "age": "25", "city": "Pune"})
#List of collections
print("List of collections:")
collections = db.list_collection_names()
for coll in collections:
print(coll)
#Dropping a collection
col1.drop()
col4.drop()
print("List of collections after dropping two of them: ")
#List of collections
collections = db.list_collection_names()
for coll in collections:
print(coll)
Wynik
List of collections:
coll
data
collection
myColl
List of collections after dropping two of them:
coll
myColl
Możesz zaktualizować zawartość istniejących dokumentów za pomocą update() metoda lub save() metoda.
Metoda aktualizacji modyfikuje istniejący dokument, natomiast metoda zapisu zastępuje istniejący dokument nowym.
Składnia
Poniżej znajduje się składnia metod update () i save () MangoDB -
>db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
Or,
db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
Przykład
Załóżmy, że utworzyliśmy kolekcję w bazie danych i wstawiliśmy do niej 3 rekordy, jak pokazano poniżej -
> use testdatabase
switched to db testdatabase
> data = [
... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
... {"_id": "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" },
... {"_id": "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
]
[
{"_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad"},
{"_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore"},
{"_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai"}
]
> db.createCollection("sample")
{ "ok" : 1 }
> db.sample.insert(data)
Poniższa metoda aktualizuje wartość miasta dokumentu o identyfikatorze 1002.
>db.sample.update({"_id":"1002"},{"$set":{"city":"Visakhapatnam"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.sample.find()
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Visakhapatnam" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
Podobnie możesz zastąpić dokument nowymi danymi, zapisując go z tym samym identyfikatorem za pomocą metody save ().
> db.sample.save({ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Vijayawada" })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.sample.find()
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Vijayawada" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Visakhapatnam" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
Aktualizowanie dokumentów za pomocą Pythona
Podobnie jak metoda find_one (), która pobiera pojedynczy dokument, metoda update_one () pymongo aktualizuje pojedynczy dokument.
Ta metoda akceptuje kwerendę określającą dokument do zaktualizowania i operację aktualizacji.
Przykład
Poniższy przykład w języku Python aktualizuje wartość położenia dokumentu w kolekcji.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['myDB']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving all the records using the find() method
print("Documents in the collection: ")
for doc1 in coll.find():
print(doc1)
coll.update_one({"_id":"102"},{"$set":{"city":"Visakhapatnam"}})
#Retrieving all the records using the find() method
print("Documents in the collection after update operation: ")
for doc2 in coll.find():
print(doc2)
Wynik
Data inserted ......
Documents in the collection:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Documents in the collection after update operation:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Visakhapatnam'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Podobnie update_many() metoda pymongo aktualizuje wszystkie dokumenty spełniające określony warunek.
Przykład
Poniższy przykład aktualizuje wartość lokalizacji we wszystkich dokumentach w kolekcji (warunek pusty) -
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['myDB']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving all the records using the find() method
print("Documents in the collection: ")
for doc1 in coll.find():
print(doc1)
coll.update_many({},{"$set":{"city":"Visakhapatnam"}})
#Retrieving all the records using the find() method
print("Documents in the collection after update operation: ")
for doc2 in coll.find():
print(doc2)
Wynik
Data inserted ......
Documents in the collection:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Documents in the collection after update operation:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Visakhapatnam'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Visakhapatnam'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Visakhapatnam'}
Podczas pobierania zawartości kolekcji można ograniczyć liczbę dokumentów w wyniku za pomocą metody limit (). Ta metoda akceptuje wartość liczbową reprezentującą liczbę dokumentów, które mają znaleźć się w wyniku.
Składnia
Poniżej znajduje się składnia metody limit () -
>db.COLLECTION_NAME.find().limit(NUMBER)
Przykład
Załóżmy, że utworzyliśmy kolekcję i wstawiliśmy do niej 5 dokumentów, jak pokazano poniżej -
> use testDB
switched to db testDB
> db.createCollection("sample")
{ "ok" : 1 }
> data = [
... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
... {"_id": "1002", "name": "Rahim", "age": 27, "city": "Bangalore"},
... {"_id": "1003", "name": "Robert", "age": 28, "city": "Mumbai"},
... {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"},
... {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"},
... {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"}
]
> db.sample.insert(data)
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 6,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
Następująca linia pobiera pierwsze 3 dokumenty z kolekcji.
> db.sample.find().limit(3)
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
Ograniczanie dokumentów za pomocą Pythona
Aby ograniczyć wyniki zapytania do określonej liczby dokumentów, pymongo udostępnia rozszerzenie limit()metoda. Do tej metody należy przekazać wartość liczbową reprezentującą liczbę dokumentów potrzebnych w wyniku.
Przykład
Poniższy przykład pobiera pierwsze trzy dokumenty w kolekcji.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['l']
#Creating a collection
coll = db['myColl']
#Inserting document into a collection
data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
{"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"},
{"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"},
{"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving first 3 documents using the find() and limit() methods
print("First 3 documents in the collection: ")
for doc1 in coll.find().limit(3):
print(doc1)
Wynik
Data inserted ......
First 3 documents in the collection:
{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}