MongoDB Insert Document example - Java @ Desk

Sunday, May 18, 2014

MongoDB Insert Document example

MongoDB Insert Document example

In MongoDB, a single document or multiple documents can be inserted into a collection by provinding a DB and a collection in the insert command.

The data points are stored in a collection specified. If the database or collection does not exists, they will automatically be created when the first data insert command is executed i.e. when we call

db.collection.insert()


Syntax for inserting a document :

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


If the collection does not exists, it creates a new collection and insert records into it.

There are 2 ways to run an insert command
1) Providing the _id field
2) Without providing _id field - During the insert, mongod will create the _id field and assign it a unique ObjectId value, as verified by the inserted document

For Example
Inserting a document without providing _id field : In this case, MongoDB will create a unique ObjectId as shown below
db.loan.insert( { item: "home", interest: 10 } )

{ "_id" : ObjectId("5063114bd386d8fadbd6b004"), "item" : "home", "interest" : 10 }


Inserting a document with _id field : In this case, MongoDB will create a unique ObjectId as shown below
db.loan.insert( { _id: 10, item: "personal", interest: 14 } )

{ "_id" : 10, "item" : "personal", "interest" : 14 }








No comments:

Post a Comment