X DevAPI User Guide

5.1 Working with Document IDs

This section describes how to work with document IDs. Every document has a unique identifier called the document ID, which can be thought of as the equivalent of a table's primary key. The document ID value is usually automatically generated by the server when the document is added, but can also be manually assigned. The assigned document ID is returned in the result of the collection.add() operation. See Section 5.1.1, “Understanding Document IDs” for more background information on document IDs.

The following example in JavaScript code shows adding a document to a collection, retrieving the added document's IDs and testing that duplicate IDs cannot be added.

mysql-js > mycollection.add({test:'demo01'})
Query OK, 1 item affected (0.00 sec)

mysql-js > mycollection.add({test:'demo02'}).add({test:'demo03'})
Query OK, 2 items affected (0.00 sec)

mysql-js > mycollection.find()
[
    {
        "_id": "00005a640138000000000000002c",
        "test": "demo01"
    },
    {
        "_id": "00005a640138000000000000002d",
        "test": "demo02"
    },
    {
        "_id": "00005a640138000000000000002e",
        "test": "demo03"
    }
]
3 documents in set (0.00 sec)

mysql-js > mycollection.add({_id:'00005a640138000000000000002f', test:'demo04'})
Query OK, 1 item affected (0.00 sec)

mysql-js > mycollection.find()
[
    {
        "_id": "00005a640138000000000000002c",
        "test": "demo01"
    },
    {
        "_id": "00005a640138000000000000002d",
        "test": "demo02"
    },
    {
        "_id": "00005a640138000000000000002e",
        "test": "demo03"
    },
    {
        "_id": "00005a640138000000000000002f",
        "test": "demo04"
    }
]
4 documents in set (0.00 sec)

mysql-js > mycollection.add({test:'demo05'})
ERROR: 5116: Document contains a field value that is not unique but required to be