
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use Variable for Collection Name in PyMongo
PyMongo is a Python distribution containing tools for working with MongoDB. Use the following syntax to use a variable for collection name −
var yourVariableName="yourCollectionName"; db[storeCollectionName].yourOperationName;
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows. We have used variable for collection name −
> var storeCollectionName="new_Collection"; > db[storeCollectionName].insertOne({"UserName":"John","UserAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5c912aea4afe5c1d2279d6a0") } > db[storeCollectionName].insertOne({"UserName":"Carol","UserAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5c912af54afe5c1d2279d6a1") } > db[storeCollectionName].insertOne({"UserName":"Mike","UserAge":27}); { "acknowledged" : true, "insertedId" : ObjectId("5c912afe4afe5c1d2279d6a2") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db[storeCollectionName].find().pretty();
The following is the output −
{ "_id" : ObjectId("5c912aea4afe5c1d2279d6a0"), "UserName" : "John", "UserAge" : 21 } { "_id" : ObjectId("5c912af54afe5c1d2279d6a1"), "UserName" : "Carol", "UserAge" : 24 } { "_id" : ObjectId("5c912afe4afe5c1d2279d6a2"), "UserName" : "Mike", "UserAge" : 27 }
Advertisements