I am a programmer and architect (the kind that writes code) with a focus on testing and open source; I maintain the PHPUnit_Selenium project. I believe programming is one of the hardest and most beautiful jobs in the world. Giorgio is a DZone MVB and is not an employee of DZone and has posted 638 posts at DZone. You can read more from them at their website. View Full User Profile

A crash course for the MongoDB console

05.16.2012
| 6313 views |
  • submit to reddit
MongoDB ships without graphical tools for database administration: in Unix style, the command line is the standard way to manually interact with the database. In this article we'll take a look at the console and to the translation of classical SQL queries into Mongo's model.

Basic

The mongo command start the console, which connects automatically to localhost and to a default database. use databaseName will switch to databaseName, which will be created in case it does not exist.

The same reasoning applies for collections: unlike for relational tables, there are no creation commands as no schema has to be specified.

The syntax is that of a JavaScript API:

db.users.find({name:"Giorgio"});

will find all JSON objects with name field equal to "Giorgio" inside the users collection in the current database.

The console is actually a fully functional JavaScript console, so you can save results of queries, declare intermediate variables, or make calculations. Note also that the shell running into the console has tab completion, so pressing Tab will attempt to complete both method names and the name of collections.

Select, count

The equivalent of SELECT queries is not that different from the Java (or another programming language) MongoDB API. You can add as many fields as you want, and the not present ones will be ignored in the search; anyway, the whole object is always extracted.

db.users.find({name:"Giorgio", type:"admin"});

extracts the users with name equal to "Giorgio" and the type equal to "admin".

db.users.count({type:"admin"});

extracts the users with type equal to "admin", that may not even have a name field.

db.users.count({"membership" : { $size : 0}});

uses the special matcher to extract users where the membership field is an array with no elements.

There are many more conditional operators, like $in, $all, $or, $and or $gt and its cousins. The syntax is intuitive and follows this example, but is clearly specified in the advanced queries tutorial.

db.users.find({"platform.name":"facebook"});

deals with subobjects, in a manner more similar to an IN than a WHERE, because the whole matching object is returned as one of the tuples of the query:

{
    "_id": ObjectId("4fb0b135e4b06f9412f1c664"),
    "platform": [{
        "name": "facebook"
    }, {
        "name": "twitter"
    }],
    "name": "Giorgio Sironi"
}

The response is beautified for readability, as it would be printed on a single line in the actual console. Of course the same descent into fields of subobjects can be performed with singular objects instead of arrays.

Finally, db.users.find().limit(3) will paginate the results, but the console won't already show more than a handful when find() is used directly.

Update

The simplest way to perform updates works in memory, but there are also in-place versions like the findAndModify() method. I felt this approach was easier while getting started:

db.users.find().forEach(function (u) { printjson(u); } );

will print to the console all the users, as the console would do with the result of find(). However, you can apply any transformation to the elements of the collection:

db.users.find().forEach(function (u) { if (u.location == 'Italy') { u.location = 'Italia'; db.users.save(u); } } );

is an example of an update query that replace objects of the users collection with location equal to "Italy" with the localized version "Italia". Of course the selection part can go into find(), but you can perform additional filtering in the most flexible way inside the callback passed to forEach(), while find() is limited to modifiers.

Delete

db.users.drop() will drop an entire collection, which will return to its initial state of empty and instantiable at the first time of need.

db.users.remove({}), like count() and find(), lets you specify a query object to filter the records to remove.

The best remove command is towards a primary key, so given a generated one this command would remove a single document:

db.users.remove({"_id": ObjectId("4d512b45cc9374271b02ec4f")});

Other binaries

mongodump is another binary that can be used to produce the dump of a database in a compressed format:

mongodump -d databaseName -o .

while mongorestore is the opposite command, importing the dump binary data into Mongo.

mongoimport and mongoexport are specular utilities that convert the database into a CSV or JSON file. mongostat and mongotop will continuously output statistics about the total load and the subdivision of running time between collections and databases.

Published at DZone with permission of Giorgio Sironi, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)