发布于 2015-09-14 14:49:33 | 84 次阅读 | 评论: 0 | 来源: 网络整理

You can write scripts for the mongo shell in JavaScript that manipulate data in MongoDB or perform administrative operation. For more information about the mongo shell see mongo 壳, and see the Running .js files via a mongo shell Instance on the Server section for more information about using these mongo script.

This tutorial provides an introduction to writing JavaScript that uses the mongo shell to access MongoDB.

Opening New Connections

From the mongo shell or from a JavaScript file, you can instantiate database connections using the Mongo() constructor:

new Mongo()
new Mongo(<host>)
new Mongo(<host:port>)

Consider the following example that instantiates a new connection to the MongoDB instance running on localhost on the default port and sets the global db variable to myDatabase using the getDB() method:

conn = new Mongo();
db = conn.getDB("myDatabase");

Additionally, you can use the connect() method to connect to the MongoDB instance. The following example connects to the MongoDB instance that is running on localhost with the non-default port 27020 and set the global db variable:

db = connect("localhost:27020/myDatabase");

If you create new connections inside a JavaScript file:

  • You cannot use use <dbname> inside the file to set the db global variable.
  • To set the db global variable, use the getDB() method or the connect() method. You can assign the database reference to a variable other than db.
  • Additionally, inside the script, you would need to call db.getLastErrorObj() or db.getLastError() explicitly to wait for the result of write operations.

Scripting

From the command line, use mongo to evaluate JavaScript.

--eval option

Use the --eval option to mongo to pass the shell a JavaScript fragment, as in the following:

mongo test --eval "printjson(db.getCollectionNames())"

This returns the output of db.getCollectionNames() using the mongo shell connected to the mongod or mongos instance running on port 27017 on the localhost interface.

evaluate a javascript file

You can specify a .js file to the mongo shell, and mongo will evaluate the javascript directly. consider the following example:

mongo localhost:27017/test myjsfile.js

This operation evaluates the myjsfile.js script in a mongo shell that connects to the test database on the mongod instance accessible via the localhost interface on port 27017.

Alternately, you can specify the mongodb connection parameters inside of the javascript file using the Mongo() constructor. See Opening New Connections for more information.

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务