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

Server-side JavaScript

Important

Map-reduce is deprecated starting in MongoDB 5.0.

MongoDB provides the following operators that perform server-side execution of JavaScript code:

  • $where operator that evaluates a JavaScript expression or a function in order to query for documents.

  • $accumulator and $function aggregation operations that allows users to define custom aggregation expressions.

You can specify a JavaScript (.js) file to mongosh to execute the file on the server. This is a good technique for performing batch administrative work. When you run mongosh on the server, connecting via the localhost interface, the connection is fast with low latency.

To disable all server-side execution of JavaScript for mongod or mongos, you can either:

Although server-side methods use JavaScript, most interactions with MongoDB do not use JavaScript but instead use an idiomatic driver in the language of the interacting application.

Refer to the individual method or operator documentation for any concurrency information. See also the concurrency table.

MongoDB 6.0 upgrades the internal JavaScript engine used for server-side JavaScript, $accumulator, $function, and $where expressions and from MozJS-60 to MozJS-91. Several deprecated, non-standard array and string functions that existed in MozJS-60 are removed in MozJS-91.

Starting in MongoDB 9.0, server-side JavaScript evaluates local Date operations in UTC, regardless of the mongod host time zone. Local getters such as Date.prototype.getHours(), local constructors and setters, and operations that convert a date to a string all use UTC. The stored BSON date value is unchanged, as are Date.prototype.getTime(), Date.prototype.toISOString(), and the getUTC*() methods.

To evaluate dates in a named time zone, use an aggregation date operator such as $hour with an explicit timezone argument. Avoid local Date methods in JavaScript. For upgrade guidance, see Compatibility Changes in MongoDB 9.0.

If you use SELinux, any MongoDB operation that requires server-side JavaScript results in a segfault error. To disable execution of server-side JavaScript, see Disable Server-Side JavaScript.