Mongoid Keys, Convert BSON::ObjectId to string, string to BSON::ObjectId


1. Convert BSON::ObjectId to string

$profile = Profile.where(“profiles_manageds.profile_fname”=>’Admin’).first
=> #<Profile _id: 4fe969dd79216d0af9000002, _type: nil, user_id: nil, organization_id: nil, email: nil, fname: “Ankit”, lname: “Mishra”, mname: “Kumar”, nickname: nil, gender: “Male”, birthdate: “15/05/1988”, firstRegistrationDate: nil, lastModifiedBy: nil, lastModifiedDate: “15/01/2011”, notes: nil, registeredById: nil, status: “active”, org_id: nil, measurements: nil, immunizations: nil, med_tests: nil, organizationsManaged: nil, parent_ids: nil, physicians: nil, profiles_manageds: [{“_id”=>BSON::ObjectId(‘4fe969dd79216d0af9000001’), “profile_id”=>”4fe9569979216d14ff000001”, “profile_fname”=>”Admin”, “profile_mname”=>”Kids”, “profile_lname”=>”link”}], registrationPayments: nil, sibling_ids: nil, organizationsAdministrated: nil, contacts: nil, default_emergencyContacts: nil, default_pickups: nil, documents: nil, child_extra_cares: nil, enrollments: nil, m_email: “”, m_fname: nil, m_lname: nil, m_phone_home: nil, m_phone_work: nil, m_phone_mobile: nil>
1.9.3-p125 :077 >
1.9.3-p125 :078 >
1.9.3-p125 :079 >   profile
=> #<Profile _id: 4fe969dd79216d0af9000002, _type: nil, user_id: nil, organization_id: nil, email: nil, fname: “Ankit”, lname: “Mishra”, mname: “Kumar”, nickname: nil, gender: “Male”, birthdate: “15/05/1988”, firstRegistrationDate: nil, lastModifiedBy: nil, lastModifiedDate: “15/01/2011”, notes: nil, registeredById: nil, status: “active”, org_id: nil, measurements: nil, immunizations: nil, med_tests: nil, organizationsManaged: nil, parent_ids: nil, physicians: nil, profiles_manageds: [{“_id”=>BSON::ObjectId(‘4fe969dd79216d0af9000001’), “profile_id”=>”4fe9569979216d14ff000001”, “profile_fname”=>”Admin”, “profile_mname”=>”Kids”, “profile_lname”=>”link”}], registrationPayments: nil, sibling_ids: nil, organizationsAdministrated: nil, contacts: nil, default_emergencyContacts: nil, default_pickups: nil, documents: nil, child_extra_cares: nil, enrollments: nil, m_email: “”, m_fname: nil, m_lname: nil, m_phone_home: nil, m_phone_work: nil, m_phone_mobile: nil>
1.9.3-p125 :080 > profile.id
=> BSON::ObjectId(‘4fe969dd79216d0af9000002’)
1.9.3-p125 :081 >
1.9.3-p125 :082 >
1.9.3-p125 :083 >   profile.id.to_s
=> “4fe969dd79216d0af9000002”

2. Convert string to BSON::ObjectId

$ profile.id.to_s
=> “4fe969dd79216d0af9000002”
1.9.3-p125 :093 > profile_id = profile.id.to_s
=> “4fe969dd79216d0af9000002”
1.9.3-p125 :094 >
1.9.3-p125 :095 >
1.9.3-p125 :096 >   profile_id
=> “4fe969dd79216d0af9000002”
1.9.3-p125 :097 >
1.9.3-p125 :098 >
1.9.3-p125 :099 >   BSON::ObjectId.from_string(profile_id)
=> BSON::ObjectId(‘4fe969dd79216d0af9000002’)

Installing MongoDB 2.0 on Ubuntu 11.10


Ubuntu 11.10 ships with an older version of MongoDB, in this article I’m going to show how to install properly the latest version MongoDB which the 2.0.1.

First you have to download the 32bit or 64bit Linux binaries and unzip the contents to /usr/local.

1 cd /tmp
2 wget http://fastdl.mongodb.org/linux/mongodb-linux-i686-2.0.1.tgz
3 sudo tar -zxf /tmp/mongodb-linux-i686-2.0.1.tgz -C /usr/local

Then you need to configure some symbolic links.

01 sudo ln -s /usr/local/mongodb-linux-i686-2.0.1 /usr/local/mongodb
02 sudo ln -s /usr/local/mongodb/bin/bsondump /usr/local/bin/bsondump
03 sudo ln -s /usr/local/mongodb/bin/mongo /usr/local/bin/mongo
04 sudo ln -s /usr/local/mongodb/bin/mongod /usr/local/bin/mongod
05 sudo ln -s /usr/local/mongodb/bin/mongodump /usr/local/bin/mongodump
06 sudo ln -s /usr/local/mongodb/bin/mongoexport /usr/local/bin/mongoexport
07 sudo ln -s /usr/local/mongodb/bin/mongofiles /usr/local/bin/mongofiles
08 sudo ln -s /usr/local/mongodb/bin/mongoimport /usr/local/bin/mongoimport
09 sudo ln -s /usr/local/mongodb/bin/mongorestore /usr/local/bin/mongorestore
10 sudo ln -s /usr/local/mongodb/bin/mongos /usr/local/bin/mongos
11 sudo ln -s /usr/local/mongodb/bin/mongosniff /usr/local/bin/mongosniff
12 sudo ln -s /usr/local/mongodb/bin/mongostat /usr/local/bin/mongostat

All you need to do now is to setup the Linux service which will be used to start MongoDB server, to do so download this script.

1 wget https://github.com/ijonas/dotfiles/raw/master/etc/init.d/mongod
2 sudo mv mongod /etc/init.d/mongod
3 sudo chmod +x /etc/init.d/mongod

After this, you’ll need to create a new system user ‘mongodb’ and prepare some folders.
1 sudo useradd mongodb
2 sudo mkdir -p /var/lib/mongodb
3 sudo mkdir -p /var/log/mongodb
4 sudo chown mongodb.mongodb /var/lib/mongodb
5 sudo chown mongodb.mongodb /var/log/mongodb

And finally you need to activate you MongoDB service’s by adding it to your system’s run-level. That way the service will startup during the boot sequence and stop nicely during the OS shutdown procedure.

1 sudo update-rc.d mongod defaults

That’s all, now you have a cleanly installed MongoDB on your server.

What is the difference between embedded and referenced


Relations are associations between one model and another in the domain and in the database. 

Embedded:

Embedded relations describe documents who are stored inside other documents in the database. Embedded relations are associations between one or many objects where the child object is embedded within the parent in the same document in the database

Referenced:

Referenced relations describe documents that reference documents in another collection by storing data (usually an id) about the other document in itself. In other word Referenced relations are associations between documents that reside in separate collections.

Mongodb queries


Here is the some important frequently used mongodb queries.

After running mongodb server(mongod) and  interactive shell(mongo),  Our’s first command should be

1. help

->Which will show a lot  of useful command that is helpful at any instance working with mongodb.

2.db.help();

->It is database level help command that will show some of data level command.

3. db.help;

-> This command will show database level methods.

All above command is basic mongodb command.

How to create database?

1. use databasename;

In my case it is “use mongotest”,  here USE  is command to create database and  mongotest is database name. It is one of the nice feature of mongodb if there will be no database with this particular name, will create new database else use(move) to exiting database.

 Create table!!!!!!!

1. db.tablename.save({“name”:”ankit”,”phone”:”09533667506″});

Fetch data from tables!!!!!!!!!!

1. db.tablename.find();

return data of table.

2.db.tablename.find;

return methods it self.

Create another record!!!!!!!!!

x={“name”:”abhay”,”phone”:”09932329856″}

db.contacts.save(x);

this is another way of creating new record and saving as an object.

Fetch particular record from tables !!!!!!!!!!

db.contacts.find({“name”:”ankit”});

N.T. -> Search option is case sensetive.

find record using id

> db.contacts.find({_id:ObjectId("4ea3aa28eaaf3871b0549dfa")});
{ "_id" : ObjectId("4ea3aa28eaaf3871b0549dfa"),
 "name" : "ankit", "phone" : "09533607506" }

Update particular record into tables !!!!!!!!!!

-> there is two way to update table

1. Using save()->this is one of nice feature to mongodb, if there will already row in table it will update with new attribute else will create new record.

2. Using update()->will only update exiting record.

find record using object

> x = db.contacts.findOne({"name":"ankit"});
{
        "_id" : ObjectId("4ea3aa28eaaf3871b0549dfa"),
        "name" : "ankit",
        "phone" : "09533607506"
}
Now we have object x with reference of contacts table.
> x
{
        "_id" : ObjectId("4ea3aa28eaaf3871b0549dfa"),
        "name" : "ankit",
        "phone" : "09533607506"
}

Now i am going to add new attribute email

> x.email = "ankit@gmail.com"
ankit@gmail.com
Let's see updated row 
> x
{
        "_id" : ObjectId("4ea3aa28eaaf3871b0549dfa"),
        "name" : "ankit",
        "phone" : "09533607506",
        "email" : "ankit@gmail.com"
}

Now we fetch details from table

> db.contacts.find();
{ "_id" : ObjectId("4ea3aa28eaaf3871b0549dfa"),
 "name" : "ankit", "phone" : "09533607506" }
{ "_id" : ObjectId("4ea3b067eaaf3871b0549dfb"),
 "name" : "abhay", "phone" : "9932326589" }

table is not updated here, we need to update table.

> db.contacts.save(x);
Now try again
> db.contacts.find();
{ "_id" : ObjectId("4ea3b067eaaf3871b0549dfb"), 
"name" : "abhay", "phone" : "9932326589" }
{ "_id" : ObjectId("4ea3aa28eaaf3871b0549dfa"),
 "name" : "ankit", "phone" : "09533607506",
 "email" : "ankit@gmail.com" }

Delete particular record from tables !!!!!!!!!!

> db.contacts.remove(x);
let's see row is there or not
> db.contacts.find();
{ "_id" : ObjectId("4ea3b067eaaf3871b0549dfb"),
 "name" : "abhay", "phone" : "9932326589" }
yah, this row is deleted
THAT ALL WAS THE CRUD OPERATION ON MONGODB TABLE.

Introduction to mongodb


What is mongodb?

->MongoDB (from “humongous”) is an open source, scalable, high-performance, schema-free, document-oriented database written in the C++ programming language.

->MongoDB has a variety of features designed to bridge the gap between key/value stores and and traditional RDBMSes; some of these features are

1.ad hoc querying

2. secondary indexes

3. replication

4. aggregation.

What is Ad hoc queries?

->In MongoDB, any field can be queried at any time. MongoDB supports range queries, regular expression searches, and other special types of queries in addition to exactly matching fields. Queries can also include user-defined JavaScript functions (if the function returns true, the document matches).

Queries can return specific fields of documents (instead of the entire document), as well as sorting, skipping, and limiting results.

What is secondary indexes ?

->By default MongoDB creates index on _id key in document. But when we ensure additional index (secondary like in InnoDB from MySQL) and query it after, engine scans it and then selective scan _id index to get documments offsets.

What is replication ?

->MongoDB supports master-slave replication. A master can perform reads and writes. A slave copies data from the master and can only be used for reads or backup (not writes).

MongoDB allows developers to guarantee that an operation has been replicated to at least N servers on a per-operation basis.

What is aggregatoin ?

->Mongodb database supports a couple of tools for aggregation,like group function similar to SQL’s GROUP BY.

e.g. count(), desticnt(), group()………..

BSON


Bin­ary JSON, is a bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments. Like JSON, BSON sup­ports the em­bed­ding of doc­u­ments and ar­rays with­in oth­er doc­u­ments and ar­rays.

BSON can be com­pared to bin­ary inter­change for­mats, like Proto­col Buf­fers. BSON is more “schema-less” than Proto­col Buf­fers, which can give it an ad­vant­age in flex­ib­il­ity but also a slight dis­ad­vant­age in space ef­fi­ciency (BSON has over­head for field names with­in the seri­al­ized data).

JSON


JSON (JavaScript Object Notation) is a lightweight data-interchange format.

-> JSON is text-based open standard designed for human-readable data interchange.

->A Web data publishing format that is designed to be both easily human — and machine — readable.

->Simple format for data exchange over the internet (used as an alternative to XML)

->The JSON is used for data interchange between programs, an area in which the ubiquitous XML is not too well-suited.

->it’s largely adopted and supported by the most part of programming languages.

->it’s a language-independent format..

->can be compressed in one line to reduce stream size.

->can represent the most part of standard objects.

->seamlessly integrates with JavaScript which makes JSON the standard for streaming data over AJAX calls.