Search This Blog

Monday, December 23, 2013

Mongo shell

Important note: This article is in relation to online MongoDB course. For more information about the course and other posts describing its content please check my main page here: M101P: MongoDB for Developers course

The interactive shell is called mongo. It is JavaScript interpreter. Everything it interprets is a JavaScript code.

Default variables
$ mongo
MongoDB shell version: 2.4.8
connecting to: test
> db
> show dbs
local   0.078125GB
m101    0.203125GB
test    (empty)
> use m101
switched to db m101
> db

You can even run some JavaScript code to implement more sophisticated behavior wehn interacting with data base.
> for ( var i =1 ; i<5; i++ ) { print(i) }

_ID document attribute

Every retrieved document from database has an attribute '_id'.
> db.funnynumbers.findOne()
{ "_id" : ObjectId("50778ce69331a280cf4bcf7d"), "value" : 87 }

It is used by the MongoDB engine internally. It is used as a PRIMARY KEY for collection for example.

The _id is immutable. To change it you can remove and insert a document again into db.

The _id is dynamically calculated when you insert documents into db. To grantee that there are no collision its value will be based on current time and process id.
> db.funnynumbers.findOne()
{ "_id" : ObjectId("50778ce69331a280cf4bcf7d"), "value" : 87 }

> db.funnynumbers.find( {'rado' : 1} )
{ "_id" : ObjectId("52b251f995aed72de4e6ed38"), "rado" : 1 }

JavaScript script to populate the data base

In the week2 we can find a JavaScript code that uses the power and flexibility of the mongo shell to creates the collection and insert documents:
~/mongo-course/M101P/week2# mongo < create_student_collection.d59b66847ae9.js
MongoDB shell version: 2.4.8
connecting to: test
switched to db school


No comments:

Post a Comment