a blog for those who code

Monday, 28 July 2014

All about MongoDB Collections

MongoDB collections are equivalent to relational database tables but only fundamentally, functionally MongoDB collections are totally different than relational database tables.

You can specify if you want a collection object to actually be created at the time you specify it or it will be created only after first row is added.

var db = new mongodb.Db('db_name', connection);

1. db.collection('collectn', function(err, collection){});

2. db.createCollection('collectn', function(err, collection){});

The difference between the above code is that the first statement doesn't create the actual collection but the second statement does.

If you use db.createCollection on an existing collection, you will get access to the collection, it won't overwrite the existing collection.Note that both methods return a collection object, which you can use to add, modify or retrieve data from the collection.

If you want to completely drop the collection, use db.dropCollection.

db.dropCollection('collectn', function(err, result){})

Remove method

The remove method removes document from collections. It takes three optional parameters.

1. selector for the documents. If its not provided, all documents are removed.
2. An optional safe mode indicator.
3. A callback function (its required is safe mode indicator is set to true)

For example..

collection.remove(null, {safe : true}, function(err, result)
 if(!err) {
console.log('result of remove method ' + result);

Insert method

Insert method inserts a new document into the collection. It also takes three parameters -

1. document or documents to be inserted.
2. an options parameter.
3. and an callback function.

The options for insert are :

1. safe mode
2. keepGoing : You have to set it to true if you wish to have your application continue if one of the documents generates an error.
3. serializeFunctions : serialize functions on the document.

For example..

collection.insert(document, {safe:true}, function(err, result){
if(err) {
 }else {

Note that MongoDB generates a unique system identifier for each document, so you can access documents with this identifier for future use.

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment