Удалить коллекцию mongodb python

How To Drop MongoDB Database And Collection Use Pymongo In Python

In previous article ( How To Connect MongoDB And Create Database Collection In Python Source Code ), we have tell you how to connect to mongoDB server, how to create database and collection use pymongo library in python. In this article we will show you example about how to delete mongoDB collection and database use pymongo in python source code.

1. Drop MongoDB Collection Use Pymongo.

There are two way to drop mongoDB collection.

    Use collection object’s drop() method. This method do not return anything, you need to verify the collection has been deleted.

from pymongo import MongoClient db_host = 'localhost' db_port = 27017 # get mongoDB database server connection object. client = MongoClient(db_host, db_port) # get mongoDB database db = client[db_name] # get mongoDB collection collection = db[collection_name] # invoke collection's drop() method to delete it. collection.drop()
# get the database object. db = client[db_name] # invoke db's drop_collection() method to drop a collection and return a python dictionary object. response = db.drop_collection(collection_name) # if the returned dictionary object contains 'ns' key. if 'ns' in response: print('Database : ', db_name, ', Collection : ', collection_name, ' has been dropped. ') # if the response contains 'errmsg' key. elif 'errmsg' in response: print('Database : ', db_name, ', Collection : ', collection_name, ' drop error : ', response['errmsg'], ', Code Name : ', response['codeName'])

2. Drop MongoDB Database Use Pymongo.

There are also two way to drop a mongoDB database use pymongo in python.

    Use pymongo.MongoClient class’s drop_database(db_name) method.

# import pymongo.MongoClient, we will use this class to create MongoDB database server connection object. from pymongo import MongoClient # database host and port number are saved in global variable. db_host = 'localhost' db_port = 27017 # get MongoDB database server connection object. client = MongoClient(db_host, db_port) result = client.drop_database(db_name)
db = client[db_name] # get all collection name list. collection_name_list = db.list_collection_names() # loop in the collection name list and drop each collection. for collection_name in collection_name_list: db.drop_collection(collection_name)

3. Drop MongoDB Collection And Database Example.

''' Created on Sep 9, 2020 @author: songzhao ''' import sys # import pymongo. import pymongo # import pymongo.MongoClient, we will use this class to create MongoDB database server connection object. from pymongo import MongoClient # database host and port number are saved in global variable. db_host = 'localhost' db_port = 27017 # get MongoDB database server connection object. client = MongoClient(db_host, db_port) # check whether the database exist or not. def is_mongo_db_exist(db_name): # get all database name list. db_list = client.list_database_names() if db_name in db_list: print('Mongo database ', db_name, ' exist.') return True else: print('Mongo database ', db_name, ' do not exist.') return False ''' Check whether the collection exist or not. ''' def is_collection_exist(db_name, collection_name): # get the database. db = client[db_name] # get collection list in the database. collection_name_ist = db.list_collection_names() if collection_name in collection_name_ist: print('Database : ', db_name, ', Collection : ',collection_name ,' exist.') return True else: print('Database : ', db_name, ', Collection : ',collection_name ,' do not exist.') return False ''' This function will drop a collection by invoke the collection's drop() method. But the drop() method do not return anything. You should confirm the collection has been dropped by query it again and return none. ''' def drop_collection(db_name, collection_name): # make sure the collection exist in the database. if is_collection_exist(db_name, collection_name): # get the database. db = client[db_name] # get the collection. collection = db[collection_name] # drop the collection by invoke the collection's drop() method. collection.drop() print('Database : ', db_name, ', Collection : ', collection_name, ' has been dropped. ') else: print('Database : ', db_name, ', Collection : ', collection_name, ' do not exist. ') ''' This function use MongoDB db's drop_collection() method to drop a collection. The drop_collection() method will return a response object which is a python dictionary. If the response dictionary contains key 'ns', then it means the collection has been dropped successfully. If the drop action has error, then the response dictionary will contains key 'errmsg', you can get it to see detail error message. ''' def drop_collection_return_response(db_name, collection_name): # If the dropped collection exist. if is_collection_exist(db_name, collection_name): # get the database object. db = client[db_name] # invoke db's drop_collection() method to drop a collection and return a python dictionary object. response = db.drop_collection(collection_name) # if the returned dictionary object contains 'ns' key. if 'ns' in response: print('Database : ', db_name, ', Collection : ', collection_name, ' has been dropped. ') # if the response contains 'errmsg' key. elif 'errmsg' in response: print('Database : ', db_name, ', Collection : ', collection_name, ' drop error : ', response['errmsg'], ', Code Name : ', response['codeName']) else: print('Database : ', db_name, ', Collection : ', collection_name, ' do not exist. ') ''' This function will drop a MongoDB database use pymongo.MongoClient class's drop_database() method. ''' def drop_database_by_mongo_client(db_name): result = client.drop_database(db_name) print('Database : ', db_name, ' has been dropped. ') is_mongo_db_exist(db_name) ''' This function will drop all collections in a database, then the database will be dropped automatically. ''' def drop_database_by_collection(db_name): db = client[db_name] # get all collection name list. collection_name_list = db.list_collection_names() # loop in the collection name list and drop each collection. for collection_name in collection_name_list: db.drop_collection(collection_name) print('Database : ', db_name, ' has been dropped. ') # after drop all collection then the database will be dropped automatically. is_mongo_db_exist(db_name) if __name__ == '__main__': db_name = 'user_account' collection_name = 'account_detail' drop_collection_return_response(db_name, collection_name) is_collection_exist(db_name, collection_name) db_name = 'test_db' collection_name = 'test_collection' drop_collection(db_name, collection_name) is_collection_exist(db_name, collection_name) db_name = 'test_db' drop_database_by_collection(db_name) db_name = 'user_account' drop_database_by_mongo_client(db_name)

Below is above example execution output.

Database : user_account , Collection : account_detail exist. Database : user_account , Collection : account_detail has been dropped. Database : user_account , Collection : account_detail do not exist. Database : test_db , Collection : test_collection exist. Database : test_db , Collection : test_collection has been dropped. Database : test_db , Collection : test_collection do not exist. Database : test_db has been dropped. Mongo database test_db do not exist. Database : user_account has been dropped. Mongo database user_account do not exist.

Источник

Читайте также:  Nginx php proxy cache

Создание и удаление коллекции с помощью PyMongo

В следующей программе мы создали коллекцию с именем testers.

import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") #use database named "organisation" mydb = myclient["organisation"] #new collection named "testers" mycol = mydb["testers"]

Примечание. Коллекция фактически создается, когда в ней есть контент. Итак, только когда в коллекции есть хотя бы один документ, вы можете увидеть, что она создается при запуске функции list_collection_names().

В следующем примере мы создали коллекцию, вставили документ и затем перечислили.

import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") #use database named "organisation" mydb = myclient["organisation"] #use collection named "testers" mycol = mydb["testers"] #a document tester = < "name": "Saranya", "address": "Kochi" >#insert a document to the collection x = mycol.insert_one(tester) print("List of Collections\n--------------------") #list the collections for coll in mydb.list_collection_names(): print(coll)

Создание коллекции с помощью PyMongo

На приведенном выше снимке экрана мы запустили программу в python для вывода списка коллекций, присутствующих в экземпляре MongoDB. Затем мы запустили указанную выше программу, в которой создали коллекцию mongodb и вставили в нее документ.

Удаление коллекции

  1. Создайте клиента для экземпляра MongoDB.
  2. Выберите базу данных с помощью клиентского объекта. Предполагается, что коллекция, которую мы собираемся удалить, присутствует в этой базе данных.
  3. Выберите коллекцию, используя объект базы данных.
  4. Используйте функцию drop() для объекта коллекции, чтобы полностью удалить указанную коллекцию из базы данных.

Пример

В следующем примере мы удалим коллекцию разработчиков. Также для понимания распечатаем список коллекций, присутствующих в базе данных до и после удаления коллекции.

import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") #use database named "organisation" mydb = myclient["organisation"] print("List of collections before deletion\n--------------------------") for x in mydb.list_collection_names(): print(x) #get collection named "developers" mycol = mydb["developers"] #delete or drop collection mycol.drop() print("\nList of collections after deletion\n--------------------------") for x in mydb.list_collection_names(): print(x)

Источник

Читайте также:  Oracle java se subscription

How to Delete or Drop Collection in MongoDB using Python?

To delete a MongoDB Collection in Python language, we shall use PyMongo. Follow these steps to delete a specific MongoDB Collection.

  1. Create a MongoDB Client to the MongoDB instance.
  2. Select database using client object. It is assumed that the collection we are going to delete is present in this database.
  3. Select collection using the database object.
  4. Use drop() function on the collection object to completely delete the specified collection from the database.

Examples

1. Delete MongoDB collection whose name is “developers”

In the following example, we shall delete developers collection. Also, for understanding, we will print the list of collections present in the database before and after deleting the collection.

Python Program

import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") #use database named "organisation" mydb = myclient["organisation"] print("List of collections before deletion\n--------------------------") for x in mydb.list_collection_names(): print(x) #get collection named "developers" mycol = mydb["developers"] #delete or drop collection mycol.drop() print("\nList of collections after deletion\n--------------------------") for x in mydb.list_collection_names(): print(x)

Delete or Drop MongoDB Collection using PyMongo

Summary

In this PyMongo Tutorial, we learned how to delete a MongoDB collection by name using drop() function.

Источник

Python MongoDB Drop Collection

You can delete a table, or collection as it is called in MongoDB, by using the drop() method.

Example

Delete the «customers» collection:

myclient = pymongo.MongoClient(«mongodb://localhost:27017/»)
mydb = myclient[«mydatabase»]mycol = mydb[«customers»]

The drop() method returns true if the collection was dropped successfully, and false if the collection does not exist.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Читайте также:  seodon.ru - Убираем отступы по краям страницы

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью