Documents, Collections and Shell
A record in MongoDB is a document, which is a data structure composed of field and value pairs. MongoDB documents are similar to JSON objects. The values of fields may include other documents, arrays, and arrays of documents.
MongoDB stores all documents in collections. A collection is a group of related documents that have a set of shared common indexes. Collections are analogous to a table in relational databases.
Collections are made up of zero or more documents. A document can safely be thought of as a row. A document is made up of one or more fields, which are similar to columns. Collections have dynamic schemas hence, documents with different count of key-value pairs can exist within a single collection. Therefore, developers need to make sure that each query is only returning documents of a certain type or that the application code performing a query can handle documents of different key-value pairs. A collection name is an UTF-8 string but it should not be an empty string or not contain the null character should not start with system prefix ‘.’ and user-created collections can not have the $ character. Accessing collection names with characters that aren’t valid in JavaScript property names like – or starting with digit, can be accessed using variables, not just literal names. The ‘system.’ is the reserved prefix for collections.
Sub-collections helps in organizing collections by name spacing with usage of the ‘.’ character as the separator like ‘vskills.company’. Sub-collections do not have any special properties but are used by GridFS (for large file storage) to store metadata separate from content and also used by drivers to access a sub-collection of a given collection.
MongoDB groups collections into database having zero or more collections with its own permissions and separate file storage on disk thus, developers should store all data for a single application in the same database. Databases names similar to collections, is an UTF-8 string, but it should not be an empty string or cannot contain characters /, \, ., “, *, <, >, :, |, ?, $, single space and null character. Database names are case-sensitive and limited to a maximum of 64 bytes as databases are files on the disk. A fully qualified collection name for a collection is the concatenation of a database name with a collection in that database though, namespaces are limited to 121 bytes. MongoDB has few in-built databases which are
- admin – It stores authentication and user details with the new user automatically inheriting permissions for all databases. Few server-wide commands use only the admin database.
- local – It stores collections that should be local to a single server hence, not replicated.
- config – It store information about the shards when MongoDB is used in a sharded setup.
Indexes in MongoDB function much like their RDBMS counterparts.
Cursors are different as when querying MongoDB for data, it returns a cursor, which can also be processed like counting or skipping ahead, without actually pulling down data.
MongoDB is made up of databases which contain collections. A collection is made up of documents. Each document is made up of fields. Collections can be indexed, which improves lookup and sorting performance. Finally, data from MongoDB is fetched through a cursor whose actual execution is delayed until necessary.
MongoDB Shell
MongoDB has the command line shell as part of command line toolkit which can be customized and provides advanced functionality as well.
Starting the shell – To connect the mongo shell to any MongoDB instance which can be reached, specify the hostname, port and database when starting the shell as – mongo vskills-host:3896/sampleDB. Start the mongo shell and connect to MongoDB instance running on localhost with default port, as
cd <mongodb installation dir>
Type ./bin/mongo to start mongo
If the <mongodb installation dir>/bin is added to the PATH environment variable, just type mongo instead of ./bin/mongo. The command should return test, which is the default database. The mongo executable can be started with numerous options and some common options are
Option | Description |
–help | Show command line options |
–nodb | Start mongo shell without connecting to a database. |
–shell | Used in conjunction with a JavaScript file (i.e. <file.js>) to continue in the mongo shell after running the JavaScript file. |
The mongo shell provides various help methods and commands and some common are
Methods/Commands | Description |
help | Show help. |
db.help() | Show help for database methods. |
db.<collection>.help() | Show help on collection methods. The <collection> can be the name of an existing collection or a non-existing collection. |
show dbs | Print a list of all databases on the server. |
use <db> | Switch current database to <db>. The mongo shell variable db is set to the current database. |
show collections | Print a list of all collections for current database |
show users | Print a list of users for current database. |
show profile | Print the five most recent operations that took 1 millisecond or more. |
Executing External JS Files – When starting, mongo checks the user’s HOME directory for a JavaScript file named .mongorc.js. If found, mongo interprets the content of .mongorc.js before displaying the prompt for the first time. If you use the shell to evaluate a JavaScript file or expression, either by using the –eval option on the command line or by specifying a .js file to mongo, mongo will read the .mongorc.js file after the JavaScript has finished processing. The shell can also be given external JavaScript files to execute by passing them in scripts at the command line, as
$ mongo samplescript1.js samplescript2.js samplescript3.js
Run Query – The shell methods can be used from the mongo shell to run queries, as
db.<collection>.find()
Here, the db refers to the current database and the <collection> is the name of the collection to query. If the mongo shell does not accept the name of the collection as it may contain a space, hyphen, or starts with a number use an alternate syntax as
db[“3test”].find()
db.getCollection(“3test”).find()
The find() method is the JavaScript method to retrieve documents from <collection>. The find() method returns a cursor to the results; however, in the mongo shell, if the returned cursor is not assigned to a variable, then the cursor is automatically iterated up to 20 times to print up to the first 20 documents that match the query. The mongo shell will prompt Type it to iterate another 20 times. Developer can set the DBQuery.shellBatchSize attribute to change the number of iteration from the default value 20, as in the following example which sets it to 10
DBQuery.shellBatchSize = 10;
Printing – The mongo shell automatically prints the results of the find() method if the returned cursor is not assigned to a variable. To format the result, developer can add the .pretty() to the operation, as
db.<collection>.find().pretty()
In addition, developer can use the following explicit print methods in the mongo shell, as
print() to print without formatting
print(tojson(<obj>)) to print with JSON formatting and equivalent to printjson()
printjson() to print with JSON formatting and equivalent to print(tojson(<obj>))
Custom Prompt – Developer may modify the content of the prompt by creating the variable prompt in the shell. The prompt variable can hold strings as well as any arbitrary JavaScript. If prompt holds a function that returns a string, mongo can display dynamic information in each prompt. An example to create a prompt with the number of commands issued in the current session, define the following variables
cmdCount = 1;
prompt = function() {
return (cmdCount++) + “> “;
}
The prompt would then resemble the following:
1> db.collection.find()
2> show collections
3>
Another example to create a mongo shell prompt in the form of <database>@<hostnane>$ define the following variables, as
host = db.serverStatus().host;
prompt = function() {
return db+”@”+host+”$ “;
}
The prompt would then resemble the following:
<database>@<hostname>$ use records
switched to db records
records@<hostname>$
Another example to create a mongo shell prompt that contains the system up time and the number of documents in the current database, as
prompt = function() {
return “Uptime:”+db.serverStatus().uptime+” Documents:”+db.stats().objects+” > “;
}
The prompt would then resemble the following:
Uptime:5897 Documents:6 > db.people.save({name : “James”});
Uptime:5948 Documents:7 >
External Editor – In the mongo shell developer can use the edit operation to edit a function or variable in an external editor. The edit operation uses the value of environments EDITOR variable. At system prompt developer can define the EDITOR variable and start mongo with the following two operations, as
export EDITOR=vim
mongo
Then, consider the following example shell session:
MongoDB shell version: 2.2.0
> function f() {}
> edit f
> f
function f() {
print(“this really works”);
}
> f()
this really works
> o = {}
{ }
> edit o
> o
{ “soDoes” : “this” }
>
As mongo shell interprets code edited in an external editor, it may modify code in functions, depending on the JavaScript compiler. For mongo may convert 1+1 to 2 or remove comments. The actual changes affect only the appearance of the code and will vary based on the version of JavaScript used but will not affect the semantics of the code.
Exit Shell – To exit the shell, type quit() or use the <Ctrl-c> shortcut.
Apply for MongoDB Certification Now!!
https://www.vskills.in/certification/databases/mongodb-server-administrator