Write Scripts for the mongo Shell Opening New Connections Differences Between Interactive and Scripted mongo instanceof instanceof returns a boolean to test if a value is an instance of some type. For example, the following operation tests whether the _id field is an instance of type ObjectId : mydoc._id instanceof ObjectId The operation returns true . typeof typeof returns the type of a field. For example, the following operation returns the type of the _id field: typeof mydoc._id In this case typeof will return the more generic object type rather than ObjectId type. 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 MongoDB Scripting (page 265), and see the Running .js files via a mongo shell Instance on the Server (page 266) 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. From the mongo shell or from a JavaScript file, you can instantiate database connections using the Mongo() con- structor: 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"); new Mongo() new Mongo(<host>) new Mongo(<host:port>) When writing scripts for the mongo shell, consider the following: • 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 . • Write operations in the mongo shell use the “safe writes” by default. If performing bulk operations, use the Bulk() methods. See Write Method Acknowledgements (page 857) for more information. Changed in version 2.6: Before MongoDB 2.6, call db.getLastError() explicitly to wait for the result of write operations (page 73). Chapter 5. Administration 270 MongoDB Documentation, Release 3.0.4