For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

Script Considerations

The results of database queries cannot be passed inside the following contexts:

  • Class constructor functions

  • Non-async generator functions

  • Callbacks to .sort() on an array

  • JavaScript setters in classes

To access to the results of database calls, use async functions, async generator functions, or .map().

The following constructors do not work:

// This code will failclass FindResults { constructor() { this.value = db.students.find(); }} // This code will failfunction listEntries() { return db.students.find(); }class FindResults { constructor() { this.value = listEntries(); }}

Use an async function instead:

class FindResults { constructor() { this.value = ( async() => { return db.students.find(); } )(); }}

Note

You can also create a method that performs a database operation inside a class as an alternative to working with asynchronous JavaScript.

class FindResults { constructor() { } init() { this.value = db.students.find(); } }

To use this class, first construct a class instance then call the .init() method.

The following generator functions do not work:

// This code will failfunction* FindResults() { yield db.students.findOne();} // This code will failfunction listEntries() { return db.students.findOne(); }function* findResults() { yield listEntries();}

Use an async generator function instead:

function listEntries() { return db.students.findOne(); }async function* findResults() { yield listEntries();}

The following array sort does not work:

// This code will faildb.getCollectionNames().sort( ( collectionOne, collectionTwo ) => { return db[ collectionOne ].estimatedDocumentCount() - db[ collectionOne ].estimatedDocumentCount() )} );

Use .map() instead.

db.getCollectionNames().map( collectionName => { return { collectionName, size: db[ collectionName ].estimatedDocumentCount() };} ).sort( ( collectionOne, collectionTwo ) => { return collectionOne.size - collectionTwo.size;} ).map( collection => collection.collectionName);

This approach to array sort is often more performant than the equivalent unsupported code.

The following JavaScript setter does not work:

// This code will failclass TestClass { value = 1; get property() { return this.value; } // does not work: set property(value) { this.value = db.test.findOne({ value }); }}