CouchDB - Creating A Document
CouchDB - Creating A Document
Each document in CouchDB has a unique ID. You can choose your own ID that should be in
the form of a string. Generally, UUID (Universally Unique IDentifier) is used, which are
random numbers that have least chance of creating a duplicate. These are preferred to
avoid collisions.
Using −X, we can specify a custom request method of HTTP we are using, while
communicating with the HTTP server. In this case, we are using PUT method. When we use
the PUT method, the content of the url specifies the object name we are creating using the
HTTP request. Here we have to send the following −
The name of the database name in which we are creating the document.
The data of the document. −d option is used to send the data/document through
HTTP request. While writing a document simply enter your Field-Value pairs separated
by colon, within flower brackets as shown below −
{
Name : Raju
age : 23
Designation : Designer
}
Example
Using the above given syntax if you want to create a document with id 001 in a database
with name my_database, you can create it as shown below.
{"ok":true,"id":"001","rev":"1-1c2fae390fa5475d9b809301bbf3f25e"}
"rev", this indicates the revision id. Every time you revise (update or modify) a
document a _rev value will be generated by CouchDB. If you want to update or
delete a document, CouchDB expects you to include the _rev field of the revision
you wish to change. When CouchDB accepts the change, it will generate a new
revision number. This mechanism ensures concurrency control.
Verification
If you want to view the created document you can get it using the document as shown
below.
Select the database in which you want to create the document. Open the Overview page of
the database and select New Document option as shown below.
When you select the New Document option, CouchDB creates a new database document,
assigning it a new id. You can edit the value of the id and can assign your own value in the
form of a string. In the following illustration, we have created a new document with an id
001.
In this page, you can observe three options − save Document, Add Field and Upload
Attachment.
In the following illustration, we have created three fields Name, age and, Designation of the
employee.
Save Document
You can save the changes made to the document by clicking on this option. After saving, a
new id _rev will be generated as shown below.