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
How I can use a database-name with special characters like " customer_tracker-990" in MongoDB console
To use a database name with special characters like "customer_tracker-990" in MongoDB console, use the getSiblingDB() method. This method allows you to reference databases with names that contain special characters like hyphens, spaces, or other symbols.
Syntax
db.getSiblingDB("database-name-with-special-chars").collection.operation()
Sample Data
Let us add some documents to the database with special characters ?
use customer_tracker-990;
db.demo1.insertMany([
{"Name": "Chris"},
{"Name": "David"},
{"Name": "Bob"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ea4697ca7e81adc6a0b3954"),
ObjectId("5ea46980a7e81adc6a0b3955"),
ObjectId("5ea46984a7e81adc6a0b3956")
]
}
Example: Query Database with Special Characters
Display all documents from the collection using getSiblingDB() ?
db.getSiblingDB("customer_tracker-990").demo1.find();
{ "_id": ObjectId("5ea4697ca7e81adc6a0b3954"), "Name": "Chris" }
{ "_id": ObjectId("5ea46980a7e81adc6a0b3955"), "Name": "David" }
{ "_id": ObjectId("5ea46984a7e81adc6a0b3956"), "Name": "Bob" }
Key Points
- The
usecommand works for switching to databases with special characters -
getSiblingDB()is required when referencing such databases in queries - Always enclose the database name in quotes when using
getSiblingDB()
Conclusion
Use getSiblingDB("database-name") to work with MongoDB databases containing special characters. This method ensures proper database referencing regardless of naming conventions used.
Advertisements
