Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Is it possible to use variable for collection name using PyMongo?
Yes, it is possible to use variables for collection names in PyMongo. You can store the collection name as a string variable and access the collection dynamically using bracket notation or the get_collection() method.
Syntax
# Method 1: Using bracket notation collection_name = "your_collection_name" collection = db[collection_name] # Method 2: Using get_collection() method collection = db.get_collection(collection_name)
MongoDB Shell Example
First, let's see how to use variables for collection names in MongoDB shell ?
var storeCollectionName = "new_Collection";
db[storeCollectionName].insertMany([
{"UserName": "John", "UserAge": 21},
{"UserName": "Carol", "UserAge": 24},
{"UserName": "Mike", "UserAge": 27}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c912aea4afe5c1d2279d6a0"),
ObjectId("5c912af54afe5c1d2279d6a1"),
ObjectId("5c912afe4afe5c1d2279d6a2")
]
}
Query with Variable Collection Name
db[storeCollectionName].find().pretty();
{
"_id": ObjectId("5c912aea4afe5c1d2279d6a0"),
"UserName": "John",
"UserAge": 21
}
{
"_id": ObjectId("5c912af54afe5c1d2279d6a1"),
"UserName": "Carol",
"UserAge": 24
}
{
"_id": ObjectId("5c912afe4afe5c1d2279d6a2"),
"UserName": "Mike",
"UserAge": 27
}
PyMongo Implementation
In PyMongo, you can use the same approach ?
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["your_database"]
# Store collection name in variable
collection_name = "new_Collection"
# Access collection using bracket notation
collection = db[collection_name]
# Insert documents
collection.insert_many([
{"UserName": "John", "UserAge": 21},
{"UserName": "Carol", "UserAge": 24}
])
# Query documents
documents = collection.find()
for doc in documents:
print(doc)
Key Points
- Use bracket notation
db[variable]to access collections dynamically - Collection names must be strings stored in variables
- Works in both MongoDB shell and PyMongo
- Alternative: use
db.get_collection(variable)in PyMongo
Conclusion
Using variables for collection names in PyMongo is straightforward with bracket notation. This approach provides flexibility when working with dynamic collection names in your applications.
Advertisements
