- Administration >
- Administration Tutorials >
- MongoDB Scripting >
- Server-side JavaScript
Server-side JavaScript¶
在 2.4 版更改: The V8 JavaScript engine, which became the default in 2.4, allows multiple JavaScript operations to execute at the same time. Prior to 2.4, MongoDB operations that required the JavaScript interpreter had to acquire a lock, and a single mongod could only run a single JavaScript operation at a time.
概述¶
MongoDB supports the execution of JavaScript code for the following server-side operations:
- mapReduce and the corresponding mongo shell method db.collection.mapReduce(). See 映射化简 for more information.
- eval command, and the corresponding mongo shell method db.eval()
- $where operator
- Running .js files via a mongo shell Instance on the Server
JavaScript in MongoDB
Although the above operations use JavaScript, most interactions with MongoDB do not use JavaScript but use an idiomatic driver in the language of the interacting application.
You can disable all server-side execution of JavaScript, by passing the --noscripting option on the command line or setting security.javascriptEnabled in a configuration file.
Running .js files via a mongo shell Instance on the Server¶
You can run a JavaScript (.js) file using a mongo shell instance on the server. This is a good technique for performing batch administrative work. When you run mongo shell on the server, connecting via the localhost interface, the connection is fast with low latency.
The command helpers provided in the mongo shell are not available in JavaScript files because they are not valid JavaScript. The following table maps the most common mongo shell helpers to their JavaScript equivalents.
Shell Helpers | JavaScript Equivalents |
---|---|
show dbs, show databases | db.adminCommand('listDatabases')
|
use <db> | db = db.getSiblingDB('<db>')
|
show collections | db.getCollectionNames()
|
show users | db.getUsers()
|
show roles | db.getRoles({showBuiltinRoles: true})
|
show log <logname> | db.adminCommand({ 'getLog' : '<logname>' })
|
show logs | db.adminCommand({ 'getLog' : '*' })
|
it | cursor = db.collection.find()
if ( cursor.hasNext() ){
cursor.next();
}
|
Concurrency¶
Refer to the individual method or operator documentation for any concurrency information. See also the concurrency table.