DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Data Engineering
  3. Databases
  4. A crash course for the MongoDB console

A crash course for the MongoDB console

Giorgio Sironi user avatar by
Giorgio Sironi
·
May. 16, 12 · Interview
Like (0)
Save
Tweet
Share
12.38K Views

Join the DZone community and get the full member experience.

Join For Free
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.

Console (video game CLI) Database Relational database MongoDB Crash (computing)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Full Lifecycle API Management Is Dead
  • Introduction to Containerization
  • mTLS Everywere
  • Application Architecture Design Principles

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: