Common MongoDB Commands

4 minute read

I’ve been updating this MongoDB+Express+Node demo for a while, (Angular part is on its way), thought it would be a good idea to document some MongoDB notes here.

And I recommend the Mongo University resource for those who just get starting with Mongo, the tutorials are great.

Setup

The install steps for Mongo aren’t complicated, I am gonna assume all the following steps happen in a Mac OS environment.

Get Started

Once installed correctly, you may want to get into the mongo shell:

$ mongo //enter mongo shell
> use [someDB] //enter some database
> db.mycollection.find() //display all result of this collection: mycollection

The default path for mongo to save data is in /data/db as you can see here, if you’d prefer to save it somewhere else:

$ mongod --dbpath ~/Desktop/somewhereelse \\don't forget it is mongod

CRUD

Let’s continue and assume the collections we are going to use are called ‘blogs’ and ‘users’.

Create

> db.users.insert( {name:"user1", age:15, industry:"IT" } )

Now let’s see if this data is saved by:

> db.users.find()
result: { "_id" : ObjectId("5450d6f0558cb30e579c239c"), "name" : "user1", "age" : 15, "industry" : "IT" }

The _id is an unique primary key for each document, in this case, it is generated by mongodb, but you can always create customized unique primary key.

Another thing worth pointing out is that, in mongodb shell, it can interpret js as well. So you can do things like:
> for(var i=0;i<10;i++){db.users.insert( {name:i, age:i*12, industry:"freelancer"} )}, you’ll get:

 "_id" : ObjectId("5450d6f0558cb30e579c239c"), "name" : "user1", "age" : 15, "industry" : "IT" }
{ "_id" : ObjectId("5450d827558cb30e579c239d"), "name" : 0, "age" : 0, "industry" : "freelancer" }
{ "_id" : ObjectId("5450d827558cb30e579c239e"), "name" : 1, "age" : 12, "industry" : "freelancer" }
{ "_id" : ObjectId("5450d827558cb30e579c239f"), "name" : 2, "age" : 24, "industry" : "freelancer" }
{ "_id" : ObjectId("5450d827558cb30e579c23a0"), "name" : 3, "age" : 36, "industry" : "freelancer" }
{ "_id" : ObjectId("5450d827558cb30e579c23a1"), "name" : 4, "age" : 48, "industry" : "freelancer" }
{ "_id" : ObjectId("5450d827558cb30e579c23a2"), "name" : 5, "age" : 60, "industry" : "freelancer" }
{ "_id" : ObjectId("5450d827558cb30e579c23a3"), "name" : 6, "age" : 72, "industry" : "freelancer" }
{ "_id" : ObjectId("5450d827558cb30e579c23a4"), "name" : 7, "age" : 84, "industry" : "freelancer" }
{ "_id" : ObjectId("5450d827558cb30e579c23a5"), "name" : 8, "age" : 96, "industry" : "freelancer" }
{ "_id" : ObjectId("5450d827558cb30e579c23a6"), "name" : 9, "age" : 108, "industry" : "freelancer" }

Read

find

db.users.find({ age: 24 })
db.users.find({ age: 24, name:2 })
db.users.find({ age: 24 }, {name:1, industry:1, _id:0})
//the first param is the query criteria, the second param is projection, which means I want which data to be returned, by default the result includes _id as you can see in above result, but you can adjust by passing 0 to '_id', the result would be:
{ "name" : 2, "industry" : "freelancer" }

findOne

Similar to find().

$gt, $lt

db.users.find({age: {$gt: 30}})
//matches users whoes age are greater than 30

$exists, $type, $regex

db.blogs.find({tags: {$type: 2}})
//matches documents containing a tags field that is either a string or an array

db.blogs.find({tags: {$exists: true}})
//matches documents which has the tag data

db.users.find({tags: {name: 'ing$'}})
//matches documents has name field and matches the reg pattern

Querying with dot notation

It is very common to see embedded structure in json, in that case, if we want to query something deep in the structure, we should use dot notation:

db.users.find( { 'userinfo.address': 'ABC123' } )

Count Results

Sometimes you don’t need specific results, but just the total number of the matches result, you can replace the find with count to get the number.

Update

Update them all

db.users.update({name: 'jen'}, {phone: 123})

Using the db.collection.update requires finding a document and utilizing the second param to replace the old document, the important thing here is that, if you do the above commands, there will be no field name in it but just the phone field, that means you need to put the whole document to get what you want.

$set, $unset

As described above, it is inefficient to fill in the whole document when you only want to update/add one field. That’s when the $set comes in handy:

{
  _id: 100,
  sku: "abc123",
  quantity: 250,
  instock: true,
  reorder: false,
  details: { model: "14Q2", make: "xyz" },
  tags: [ "apparel", "clothing" ],
  ratings: [ { by: "ijk", rating: 4 } ]
}

Use $set to update fields:

db.products.update(
   { _id: 100 },
   { $set:
      {
        quantity: 500,
        details: { model: "14Q3", make: "xyz" },
        tags: [ "coats", "outerwear", "clothing" ]
      }
   }
)

Upserts

It is also likely that you want to either update sth if it already exists or add sth if it’s not exist yet:

db.users.update({name:'jen'},{$set:{age:36}},{upsert:true})

Multi-update

Update multiple documents:

db.user.update({},{$set:{title:'Manager'}})

In this command, the update seems to matches all documet, but in MongodDB, even if you set the first param like this, the execution still happens by one document, so if we want this manager set to be implemented to all documents, let’s add another option:

db.user.update({},{$set:{title:'Manager'}}, {multi:true})

$push, $pop, $pull, $pushAll, $pullAll, $addToSet

see this link for more info

Remove

Each collection has a method remove, which has a similar syntax as find, if you specify an empty document to remove, then all documents in this collection will be removed, although if cleaning up this collection is your goal, it would be better to use drop(). The difference is that remove is executed one by one ,and drop is faster.

Tags: , ,

Updated: