MongoDB: CRUD

With a bit of intro, lets get to some work with MongoDB.

CRUD in programming terms often refers to, C: Create, R: Read, U: Update, D: Delete Operations. So how do we achieve them?

Create

MongoDB shell version: 1.2.2
url: test
connecting to: test
type "exit" to exit
type "help" for help

> use studDB
switched to db studDB

## Add field
> db.stud.save({id:1,name:'Alice',grade:'A'})

## Other way to add field
> field={id:3,name:'Chetan',grade:'C'}                                            
{ "id" : 3, "name" : "Chetan", "grade" : "C" }

> db.stud.save(field)

Read

## All fields
> db.stud.find().forEach(printjson)
{
    "_id" : ObjectId("4fe18ba92d9041659445d3d0"),
    "id" : 1,
    "name" : "Alice",
    "grade" : "A"
}
{
    "_id" : ObjectId("4fe18d702d9041659445d3d1"),
    "id" : 3,
    "name" : "Chetan",
    "grade" : "C"
}

## First field

> db.stud.findOne()     
{
    "_id" : ObjectId("4fe18ba92d9041659445d3d0"),
    "id" : 1,
    "name" : "Alice",
    "grade" : "A"
}

Update

> db.stud.update({name:"Chetan"}, {$set:{grade:"C+"}})                                                      

> db.stud.find().forEach(printjson)
{
    "_id" : ObjectId("4fe18ba92d9041659445d3d0"),
    "id" : 1,
    "name" : "Alice",
    "grade" : "A"
}
{
    "_id" : ObjectId("4fe18d702d9041659445d3d1"),
    "id" : 3,
    "name" : "Chetan",
    "grade" : "C+"
}

Delete

> db.stud.remove({name:"Chetan"})

> db.stud.find().forEach(printjson)
{
    "_id" : ObjectId("4fe18ba92d9041659445d3d0"),
    "id" : 1,
    "name" : "Alice",
    "grade" : "A"
}

2 thoughts on “MongoDB: CRUD

  1. How could I apply this example with MongoDB + Tornadoserver asyncronos mode. Had some example an Application Asyncrona with examples below using MongoDB + TornadoServer

  2. You need to use asyncmongo to have a non-blocking way of connecting to mongodb with Tornado asnchronous.. Something like this should work..

    import asyncmongo
    import tornado.web

    class Handler(tornado.web.RequestHandler):

    @tornado.web.asynchronous
    def get(self):
    db = asyncmongo.Client(….)
    db.someoperation(….,
    callback=self._on_response)
    def _on_response(self):
    ….

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.