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
MongoDB query to retrieve records from a collection named with letters and numbers
When working with MongoDB collections that have names containing letters, numbers, hyphens, and underscores, you must use the db.getCollection() method to access them, as these names cannot be used with standard dot notation.
Syntax
db.getCollection('collection-name-with-special-chars').find();
db.getCollection('collection-name-with-special-chars').insertOne(document);
Create Sample Collection
Let's create a collection with a complex name containing letters, numbers, hyphens, and underscores ?
db.createCollection('7664734-541d-r5i5f-845575e-ghfhjrjr3747_demo368');
{ "ok" : 1 }
Insert Sample Data
Insert documents into the collection using db.getCollection() ?
db.getCollection('7664734-541d-r5i5f-845575e-ghfhjrjr3747_demo368').insertMany([
{"FirstName": "Chris"},
{"FirstName": "David"},
{"FirstName": "Bob"}
]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5e57e2152ae06a1609a00aea"),
ObjectId("5e57e21a2ae06a1609a00aeb"),
ObjectId("5e57e21e2ae06a1609a00aec")
]
}
Retrieve Records
Query all documents from the collection using find() method ?
db.getCollection('7664734-541d-r5i5f-845575e-ghfhjrjr3747_demo368').find();
{ "_id" : ObjectId("5e57e2152ae06a1609a00aea"), "FirstName" : "Chris" }
{ "_id" : ObjectId("5e57e21a2ae06a1609a00aeb"), "FirstName" : "David" }
{ "_id" : ObjectId("5e57e21e2ae06a1609a00aec"), "FirstName" : "Bob" }
Key Points
- Use
db.getCollection('collection-name')for collections with special characters - Collection names with hyphens, numbers, or underscores require this method
- Standard dot notation like
db.collection-namewill not work
Conclusion
MongoDB's db.getCollection() method allows you to work with collections that have complex names containing special characters. This approach ensures you can access and query any collection regardless of its naming convention.
Advertisements
