TL;DR:
Calling db.collection()
immediately after connection only works in versions of the driver less than 3.0.
Details:
Firstly, the official examples you sighted were from MongoDB driver at version 1.4.9
, the driver is now at version 3.5.8
, I would suggest you check out the latest documentation and examples here.
To clarify the confusion, the database path specified in the connection URI is the authentication database i.e the database used to log in, this is true even for the 1.4.9 version of the driver - reference.
However, the reason for the difference you mentioned, i.e being able to call db.collection()
immediately after a connection in some cases is a result of the change in the MongoClient class in version 3 of the driver - reference.
Before version 3, MongoClient.connect
would return a DB instance to its call back function and this instance would be referencing the database specified in the path of the connection URI, so you could call db.collection()
straight away:
MongoClient.connect("<connection_URI>", function(err, db) {
// db is a DB instance, so I can access my collections straight away:
db.collection('sample_collection').find();
});
However, an update was made at version 3 such that, MongoClient.connect
now returns a MongoClient instance not a DB
instance anymore - reference:
MongoClient.connect("<connection_URI>", function(err, client) {
// client is a MongoClient instance, you would have to call
// the Client.db() method to access your database
const db = client.db('sample_database');
// Now you can access your collections
db.collection('sample_collection').find();
});