Documentation Home
X DevAPI User Guide
Download this Manual

X DevAPI User Guide  /  Working with Result Sets  /  Working with Document IDs

Pre-General Availability Draft: 2017-05-19

9.2 Working with Document IDs

Every document has a unique identifier called the document ID, which can be thought of as the equivalent of a tables' primary key. The document ID value can be manually assigned when adding a document. If no value is assigned, a document ID is generated and assigned to the document automatically. Without knowledge of the generated IDs you cannot reliably fetch and update any of the previously inserted documents. The following methods enable you to access the document ID value from the return value of collection.add():

  • getDocumentId()

  • getDocumentIds()

Note the difference in the plural. getDocumentId() is used to get the unique identifier value when a single document is added. For example assuming that a test schema is assigned to the variable db and the collection my_collection exists:

// Get the collection
var myColl = db.getCollection('my_collection');

// Insert a document
var res = myColl.add({ name: 'Jack', age: 15, height: 1.76 }).execute();

// Print the document ID assigned to the document
print('Document Id:', res.getDocumentId());

getDocumentIds() returns a list of all document IDs for documents added. For example:

var res = collection.add({ _id: 1, name: 'Jack'}).add({ _id: 223, name: 'Jim'}).execute();

ids = res.getDocumentIds());
ids.forEach(function(id) { print(id); });

// prints 1
// prints 223

These two methods are necessary because X DevAPI supports chaining of collection.add() and table.insert() calls as one command. For example:

coll.add({name: 'Jack'}).add({age: 13}).execute();

When the above code is run two documents are added to the collection, which creates two document IDs implicitly. You can not execute getDocumentID() in this case, because multiple document IDs are returned. To access all the resulting document IDs from a chain of calls, use getDocumentIds(). To get the document ID of the most recently added document, use getDocumentId().

To retrieve the document IDs of certain documents that have been added, use getDocumentIds() and address the specific document IDs. For example:

coll.add({name: 'Jack'}).add({age: 13}).execute();
ids = res.getDocumentIds());
// [0] - first, [1] - second and last, ...

User Comments
Sign Up Login You must be logged in to post a comment.