Python Data Presistence – PyMongo – Add Collection
Create a new database object by using any name currently not in the list.
Example
>>> db=client.newdb
The Database is actually created when the first document is inserted. The following statement will implicitly create a ‘products’ collection and multiple documents from the given list of dictionary objects.
Example
>>> pricelist=[{ 'ProductID : 1 / 'Name' :'Laptop', 'price' 25000},{ 'ProductID :2, 'Name' :'TV', 'price' 40000},{ 'ProductID : 3, 'Name' :'Router', 'price' 2000},{' ProductID' 4, 'Name': 'Scanner', 'price' 'price' 5000},{' 9000}] ProductID' 5, Name': 'Printer', >>> db.products.insert_many(pricelist)
You can confirm the insertion operation by find ( ) method in the mongo shell, as we have done earlier.
We create a collection object explicitly by using the create_collection( ) method of the database object.
Example
>>> db.create_collection(1 customers')
Now, we can add one or more documents in it. The following script adds documents in ‘customers’ collection.
Example
from pymongo import MongoClient client=MongoClient() db=client.newdb db.create_collection("customers") cust=db['customers' ] custlist=[{'CustID':1,1 Name' :'Ravikumar', 'GS- TIN':'27AAJPL7103N1ZF'}, {'CustID' :2, 'Name': 'Patel', 'GSTIN': '24ASDFG1234N- 1ZN'}, {'CustID' : 3, ' Name' : 'Nitin', 'GSTIN': '27AABBC7895N- 1ZT'}, {'CustID' : 4, ' Name' : 'Nair',' GSTIN':' 32MMAF8963N1ZK'} {'CustID' :5, ' Name' : 'Shah',' GSTIN':' 24BADEF2002N- 1ZB'}, {'CustID' :6, ' Name' : 'Khurana .', 'GSTIN ':'07KABCS1002N- lZV'}, {'CustID' :7, ' Name' : 'Irfan', 'GSTIN': '05IIAAV5103N- 1ZA'}, {'CustID' :8, ' Name' : 'Kiran', 'GSTIN': '12PPSD- F22431ZC' {'CustID' }. :9, ' Name' : 'Divya', 'GSTIN': '15ABCDE1101N- 1ZA'}, {'CustID' : 10 ,'Name' :'John', 'GS- TIN':'29AAEEC4258E1ZK'}] cust.insert_many(custlist) / client.close()