Common MongoDB Commands
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:
Read
find
findOne
Similar to find()
.
$gt, $lt
$exists, $type, $regex
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:
Use $set to update fields:
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
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.