2 weeks back I attended yet another RHoK Melbourne event and ended up working on a project with NodeJS & MongoDB: both unfamiliar territories for me and thought it would be a good opportunity to create a quick start guide: here is the MongoDB one
Installing and Running the Server
- Get the binaries on the download page (http://www.mongodb.org/downloads) and get the necessary download for your platform (Windows/Linux/OS X/Solaris). Following commands will be based on OSX but similar actions can be one on other platforms
- In a terminal, navigate to where you downloaded the package and extract it
cd ~/Downloads tar -zxf mongodb-osx-x86_64-2.4.8.tgz
- Create a folder to store your database
cd mongodb-osx-x86_64-2.4.8 mkdir db
- Start the server specifying the folder created
bin/mongod --dbpath=db
Terminology coming from the typical relational database world
Relational Database | MongoDB |
---|---|
Database / Schema | Database |
Table | Collections |
Row | Record |
Field / Column | Field |
Quick start of the MongoDB Shell
- Connect to the server
Navigate to the folder where the files are extratcted, run the mongo Javascript shell (which has tab completion)cd ~/Downloads/mongodb-osx-x86_64-2.4.8 bin/mongo
- List / show databases
show dbs
- Select a database (no need to created a database)
> use unicorn switched to db unicorn > db unicorn
- Show collections (tables)
show collections
- Inserting a record (row in a table)Collections do not need to be initialised, they are auto generated.
Below shows the output of the Mongo shell. system.indexes contains indexes for collections> show collections > db.unicorns.insert({name: 'Aurora', gender: 'f', weight: 450}) > show collections system.indexes unicorns
Mismatched fields
db.unicorns.insert({name: 'Aurora', gender: 'f', weight: 450}) db.unicorns.insert({name: 'Leto', gender: 'm', home: 'Arrakeen', worm: false})
Arrays
db.unicorns.insert({ name: 'Solnara', loves:['apple', 'carrot', 'chocolate']})
- Listing / Querying records
> db.unicorns.find() { "_id" : ObjectId("52b65132eb122da0e6dd19a9"), "name" : "Aurora", "gender" : "f", "weight" : 450 } { "_id" : ObjectId("52b6519127026146f128de90"), "name" : "Leto", "gender" : "m", "home" : "Arrakeen", "worm" : false }
Items have _id auto generated. No need to set an auto increment field.
Filtering and field selection
db.collection.find( {andedFilters}, {fieldWith1AsShow0asHide} )
Search by name and show only name and worm fields
> db.unicorns.find({name: 'Aurora'}, {name: 1, worm:1, _id: 0}) { "name" : "Aurora" } > db.unicorns.find({ $or: [{name: 'Aurora'}, {'name': 'Leto'}]}, {name: 1, worm:1, _id: 0} ) { "name" : "Leto", "worm" : false } { "name" : "Aurora" }
Paging and Limiting results
db.unicorns.find().skip(1).limit(2)
Record Counting
db.unicorns.count() db.unicorns.find({'name' : 'Aurora'}).count()
Distinct
db.unicorns.distinct('name') db.unicorns.distinct('name', {$or: [{'name' : 'Leto'}, {'name':'Aurora'}]})
- Query Selectors
- Comparison:
- $gt / $lt ($gte / $lte): Greater/Less than (or equal).
- $ne, $in / $nin: Not equal. In / Non in
- Logical: $or, $and, $not, $nor
- Comparison:
- Updating:
Update first matching recorddb.unicorns.update( { name: 'Aurora' }, { $set : { weight: 10 } } )
Update all matching records
db.unicorns.update( { name: 'Aurora' }, { $set : { weight: 10 } }, { multi: true } )
Update matching record but insert if doesn’t exist
db.unicorns.update( { name: 'Roooooodles' }, { $set : { weight: 10 } } , { upsert: true } )
- Deleting:
Deleting all records:db.unicorns.remove()
Delete all matching records
db.unicorns.remove({name: 'Aurora'})
Delete only first matching record
db.unicorns.remove({name: 'Aurora'}, true)
- Drop collection
db.unicorns.drop()
Other Considerations
- No joins. But has embedded documents
> db.unicorns.insert({name: 'Aurora', gender: 'f', weight: 1450, owner: {'name': ['You', 'Me']}}) > db.unicorns.find({'owner.name': 'Me'}, {'name': 1, 'owner.name': 1, _id: 0}) { "name" : "Aurora", "owner" : { "name" : [ "You", "Me" ] } }
Further References
- The Little MongoDB book (got a copy at the MongoDB User Group and it’s a nice short intro. Physically – 34 pages in a A5 format)
- Mongo DB Manual
- GUI-style administrative interface