Blog

Basic MongoDB Terminal Commands
Posted on July 17, 2015 in MongoDB by Matt Jennings

After installing MongoDB, below are some basic terminal commands.

Start MongoDB

Open a terminal window, become a root user, and do:
mongod

View MongoDB Database(s)

Open ANOTHER terminal window, become a rooter user, and do:
mongo

Then to show MongoDB database(s) do:
show dbs

*NOTE: Database that are created and do NOT have collection(s) (analogous to tables in MySQL) will NOT appear when you do show dbs. After you add collection(s) they will appear when you do show dbs.

Create and Switch to a Database Named test_app

use test_app

Switch to a Database that Has Already Been Created Named matt_db

use matt_db

Show the Current Database You Are In

db

Delete a Database You are Currently In

db.dropDatabase()

Create a Collection in a Database

A MongoDB collection is analogous to a MySQL table, and to create one named users in the current table you are in do:
db.createCollection("users");

Insert a Document into a Collection

A new MongoDB document can be inserted into a collection. This is analogous to inserting a new MySQL row into a table. To insert a new document into a users collection do the command below, which inserts data in a Binary JSON (BSON) format.

BSON extends JSON by including additional data types to be more efficient for encoding and decoding within different languages. Do:

db.users.insert({name: "Matt"})

Show Collects in the Database Your Are In

show collections

Delete a Collection named comments

db.comments.drop()

Clear Screen

cls

Show All Documents in a ninjas Collection

db.ninjas.find()

In an Easier-To-Read-Format, Show All Documents in a ninjas Collection

db.ninjas.find().pretty()

Find One Document for { name: "Trey" }

db.ninjas.find( {name: "Trey"} ).pretty()

Example of Querying by an ID that MongoDB Creates Automatically for Every Document

db.ninjas.find( {_id: ObjectId("55a96d10816d4bd07b2f1503")} );

Remove a {name: "Trey"} Document

db.ninjas.remove( {name: "Trey"} )

If Two Documents Have the Same Property Name and Values of {name: "Carlos"}, Only Remove one of Them

db.ninjas.remove( {name: "Carlos"}, true )

Update a Document with a { "name" : "Tiger Woods" } Property using the $set Operator

db.ninjas.update( {name: "Tiger Woods"}, {$set: {location: "Mountain View"}} )

Leave a Reply

To Top ↑