buzypi
buzypi

Reputation: 1590

Working of MongoDB's implicit collection access on calling db.<collection>

In MongoDB, when we access a collection on a db object, if the collection is undefined, it implicitly calls the getCollection function defined in DB.prototype.

I am not able to figure out where this call happens in the Mongo shell source: https://github.com/mongodb/mongo/tree/master/src/mongo/shell

How does this work?

Upvotes: 2

Views: 98

Answers (1)

Stennie
Stennie

Reputation: 65433

As at MongoDB 3.4, the mongo shell integrates with a scripting engine API that is part of the MongoDB server code base. The default collection behaviour is implemented by overriding the getProperty method of the db object: src/mongo/scripting/mozjz/db.cpp.

I don't believe there is an equivalent approach to doing this sort of autoloading in pure JavaScript, as the only default JavaScript method available is the class constructor.

Upvotes: 1

Related Questions