couchdb

How can I insert many documents at once?


When I want to insert a document using CouchDB, I send a request like this one:

POST http://localhost:5984/blogging/
Accept: application/json
Content-Type: application/json

{
    "name": "Example",
    "value": 5
}

And it Works. But, what if I want to insert two documents at once? I try:

POST http://localhost:5984/blogging/
Accept: application/json
Content-Type: application/json

[
    {
        "name": "Example 2",
        "value": 6
    },
    {
        "name": "Example 3",
        "value": 7
    }
]

And it answers me:

HTTP/1.1 400 Bad Request
Cache-Control: must-revalidate
Connection: close
Content-Length: 66
Content-Type: application/json
Date: Thu, 28 Feb 2019 08:03:52 GMT
Server: CouchDB/2.3.0 (Erlang OTP/19)
X-Couch-Request-ID: 9ed2f39fcf
X-CouchDB-Body-Time: 0

{
  "error": "bad_request",
  "reason": "Document must be a JSON object"
}

Solution

  • Well, first of all, I would suggest you to check this API from the documentation: http://docs.couchdb.org/en/stable/api/database/bulk-api.html#db-bulk-docs

    And, apart from that, you aren't sending a valid JSON object. I would change your request in this way:

    POST http://localhost:5984/blogging/_bulk_docs
    Accept: application/json
    Content-Type: application/json
    
    {
        "docs": [
            {
                "name": "Example 2",
                "value": 6
            },
            {
                "name": "Example 3",
                "value": 7
            }
        ]
    }