Thursday, 19 February 2015

mongodb : Insert one or more documents


You can insert a document into mongoDB using insert or save method.

Insert document using insert method
Syntax
db.collection.insert(
   <document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)


Parameter
Type
description
document
document or array
A document or array of documents to insert into the collection.
writeConcern
document
Optional. I will explain this in later posts
ordered
boolean
Optional. Default value is true.
If true, perform an ordered insert of the documents in the array, and if an error occurs with one of documents, MongoDB will return without processing the remaining documents in the array.
If false, perform an unordered insert, and if an error occurs with one of documents, continue processing the remaining documents in the array.



If collection don’t exist, then insert method creates a collection at the time of insertion.

_id field
If document don’t specify _id field at the time of insertion, then MongoDB will add the _id field and assign a unique ObjectId for the document before inserting. The _id value is unique in the collection.

ObjectId is a 12-byte BSON type, constructed using:

    a 4-byte value representing the seconds since the Unix epoch,
    a 3-byte machine identifier,
    a 2-byte process id, and
    a 3-byte counter, starting with a random value.

> db.employee.insert({"id":1,"firstName":"Hari Krishna","lastName":"Gurram"})
WriteResult({ "nInserted" : 1 })
>
> db.employee.find()
{ "_id" : ObjectId("54b2a8c9dbf1847bed465758"), "id" : 1, "firstName" : "Hari Krishna", "lastName" : "Gurram" }
>


In the above snippet, I insert a document into employee collection without specifying “_id” field, so mongoDB creates id for the document. “_id” field is primary key field for the document, it is used to uniquely identify the document. If you don’t specify any value for “_id” field, then mongoDB generates one for the document.

Insert document by specifying _id field
> db.employee.insert({"_id" : 2, "firstName":"Rama Krishna","lastName":"Gurram"})
WriteResult({ "nInserted" : 1 })
>
> db.employee.find()
{ "_id" : ObjectId("54b2a8c9dbf1847bed465758"), "id" : 1, "firstName" : "Hari Krishna", "lastName" : "Gurram" }
{ "_id" : 2, "firstName" : "Rama Krishna", "lastName" : "Gurram" }
>


Insert array of documents
> db.employee.insert(
 [
   {
     "id": 1,
     "firstName": "Joel",
     "lastName": "chelli"
   },
   {
     "id": 2,
     "firstName": "Ananad",
     "lastName": "Bandaru"
   },
   {
     "id": 3,
     "firstName": "Gopi",
     "lastName": "Battu"
   },
   {
     "id": 4,
     "firstName": "Ritwik",
     "lastName": "Mohenthy"
   }
 ]
 )
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 4,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})
>
> db.employee.find()
{ "_id" : ObjectId("54b2a8c9dbf1847bed465758"), "id" : 1, "firstName" : "Hari Krishna", "lastName" : "Gurram" }
{ "_id" : 2, "firstName" : "Rama Krishna", "lastName" : "Gurram" }
{ "_id" : ObjectId("54b2aa07dbf1847bed465759"), "id" : 1, "firstName" : "Joel", "lastName" : "chelli" }
{ "_id" : ObjectId("54b2aa07dbf1847bed46575a"), "id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru" }
{ "_id" : ObjectId("54b2aa07dbf1847bed46575b"), "id" : 3, "firstName" : "Gopi", "lastName" : "Battu" }
{ "_id" : ObjectId("54b2aa07dbf1847bed46575c"), "id" : 4, "firstName" : "Ritwik", "lastName" : "Mohenthy" }
>

Prevoius                                                 Next                                                 Home

mongodb : Drop collection


Syntax
db.collection_name.drop().

> show collections;
address
employee
system.indexes
>
> db.address.drop()
true
>
> show collections;
employee
system.indexes
>

Prevoius                                                 Next                                                 Home

What is capped collection?


Capped collection is a fixed size collection, that automatically overwrites its oldest entries when it reaches its maximum size.

Options
Filed
Type
Description
capped
Boolean
Optional. ‘true’ indicates it is a capped collection. For capped collections, you must also set maximum size in ‘size’ field
autoIndexId
Boolean
Optional. Specify false to disable the automatic creation of an index on the _id field.
size
Number
Optional. Specifies a maximum size in bytes for a capped collection. The size field is required for capped collections, and ignored for other collections.
max
Number
Optional. The maximum number of documents allowed in the capped collection. The size limit takes precedence over this limit. If a capped collection reaches its maximum size before it reaches the maximum number of documents, MongoDB removes old documents. If you prefer to use this limit, ensure that the size limit, which is required, is sufficient to contain the documents limit.
usePowerOf2Sizes
boolean
Optional. It is the default allocation strategy for all collections. Set to false to disable the usePowerOf2Sizes allocation strategy for this collection. By setting usePowerOf2Sizes, you ensure that MongoDB will allocate space for documents in sizes that are powers of 2. Smalles allocation for a document is 32. So it grows like 32, 64, 128, 256….


For example
> db.createCollection("address", { capped : true, size : 5242880, max : 5000 } )
{ "ok" : 1 }

Above command creates a collection named address with a maximum size of 5 megabytes and a maximum of 5000 documents.


Prevoius                                                 Next                                                 Home

mongodb : Create collection

In mongoDB, you no need to create a collection, mongoDB creates automatically, when you insert a document.

> use sample;
switched to db sample
>
>
> db.dropDatabase();
{ "dropped" : "sample", "ok" : 1 }
>
> show dbs;
admin  (empty)
local  0.078GB
test   (empty)
>
> use sample;
switched to db sample
>
> show collections;
>
> db.employee.insert({"id":1,"firstName":"Hari Krishna","lastName":"Gurram"})
WriteResult({ "nInserted" : 1 })
>
> show collections;
employee
system.indexes
>

If you want to create a collection explicitly, you can do by using “db.createCollection(collectionName, options)” command.

Syntax 
db.createCollection(name, {capped: <boolean>, autoIndexId: <boolean>, size: <number>, max: <number>, usePowerOf2Sizes : <boolean>} )

Parameter
Type
Description
name
string
The name of the collection to create.
options
document
Optional. Configuration options for creating a capped collection or for pre allocating space in a new collection.

Prevoius                                                 Next                                                 Home