I have found a collection in one of our MongoDB databases with the name my.collection
.
Is there a way to access this collection from the MongoDB shell, despite it having a point in the name?
> db.my.collection.findOne(); null
I'm pretty sure that that is not correct.
To obtain a list of MongoDB collections, we need to use the Mongo shell command show collections . This command will return all collections created within a MongoDB database. To be able to use the command, we'll first need to select a database where at least one collection is stored.
You can use read operations to retrieve data from your MongoDB database. There are multiple types of read operations that access the data in different ways. If you want to request results based on a set of criteria from the existing set of data, you can use a find operation such as the find() or findOne() methods.
Database names and Collection names are case sensitive. You can always recreate the DB/Collection with the appropriate name. The Mongo Shell is a interactive JS interpreter.
The collectionExists method can be used to check whether a collection is present or not: MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.
db: It is database object. collectionname: It is the name of the collection. 3) Accessing a Collection: To acces a MongoDB collection name use the below syntax. Note: Database_object [“Collectioname”] can be useful in the case where the name of the collection contains a space in between them i.e. in cases like database_object [“Collection name”].
Starting in MongoDB 5.0, document field names can be dollar ( $ ) prefixed and can contain periods (. ). However, mongoimport and mongoexport may not work as expected in some situations with field names that make use of these characters.
Starting in version 4.0 of the mongo shell, db.getCollectionNames () is equivalent to: For users with the required access (privileges that grant listCollections action on the database), the method lists the names of all collections for the database.
MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability.
try this instead:
db["my.collection"].findOne();
you run into the same issue with hyphens or any other name that does not match on [a-zA-Z_$][0-9a-zA-Z_$]
This limitation comes from valid named for javascript object properties.
if collection name is "my.collection"
db.my.collection.findOne(); // OK
null
if collection name is "my.1.collection"
db.my.1.collection.findOne(); // Not OK
SyntaxError: missing ; before statement
Fix:
db["my.1.collection"].findOne(); // Now is OK
null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With