Documentation Home
X DevAPI User Guide
Download this Manual

X DevAPI User Guide  /  Working with Collections  /  Collection CRUD Function Overview

Pre-General Availability Draft: 2017-09-21

4.3 Collection CRUD Function Overview

The following section explains the individual functions of the Collection object.

The most common operations to be performed on a Collection are the Create Read Update Delete (CRUD) statements. In order to speed up find operations it is recommended to make proper use of indexes.

Collection.add()

The Collection.add() function is used to store documents in the database. It takes a single document or a list of documents and is executed by the run() function.

The collection needs to be created with the Schema.createCollection() function before documents can be inserted. To insert documents into an existing collection use the Schema.getCollection() function.

The following example shows how to use the Collection.add() function. The example assumes that the test schema exists and that the collection my_collection does not exist.

MySQL Shell JavaScript Code

// Create a new collection
var myColl = db.createCollection('my_collection');

// Insert a document
myColl.add( { name: 'Sakila', age: 15 } ).execute();

// Insert several documents at once
myColl.add( [
{ name: 'Susanne', age: 24 },
{ name: 'Mike', age: 39 } ] ).execute();

MySQL Shell Python Code

# Create a new collection
myColl = db.create_collection('my_collection')

# Insert a document
myColl.add( { 'name': 'Sakila', 'age': 15 } ).execute()

# Insert several documents at once
myColl.add( [
{ 'name': 'Susanne', 'age': 24 },
{ 'name': 'Mike', 'age': 39 } ] ).execute()

Node.js JavaScript Code

// Create a new collection
db.createCollection('myCollection').then(function(myColl) {

  // Insert a document
  myColl.add( { name: 'Sakila', age: 15 } ).execute();

  // Insert several documents at once
  myColl.add( [
    { name: 'Susanne', age: 24 },
    { name: 'Mike', age: 39 }
  ] ).execute();
});

C# Code

{
// Assumptions: test schema assigned to db, my_collection collection not exists

// Create a new collection
var myColl = db.CreateCollection("my_collection");

// Insert a document
myColl.Add(new { name = "Sakila", age = 15 }).Execute();

// Insert several documents at once
myColl.Add(new[] {
new { name = "Susanne", age = 24 },
new { name = "Mike", age = 39 } }).Execute();
}

Java Code

// Create a new collection
Collection coll = db.createCollection("payments");

// Insert a document
coll.add("{\"name\":\"Sakila\", \"age\":15}");

// Insert several documents at once
coll.add("{\"name\":\"Susanne\", \"age\":24}",
        "{\"name\":\"Mike\", \"age\":39}");

C++ Code

// Create a new collection
Collection coll = db.createCollection("payments");

// Insert a document
coll.add(R"({"name":"Sakila", "age":15})").execute();

// Insert several documents at once
std::list<DbDoc> docs = {
  R"({"name":"Susanne", "age":24})",
  R"({"name":"Mike", "age":39})"
};
coll.add(docs).execute();

The following diagram shows the full syntax definition.

Figure 4.1 Collection.add() Syntax Diagram

Collection.add() Syntax Diagram

Document Identity

Every document has a unique identifier called the document ID. The document ID is stored in the _id field of a document. The document ID is a string with a maximum length of 32 characters.

You do not need to provide the _id field manually. As shown, documents can be inserted without the field. If no _id field is given, a unique value is generated. Auto generated values are reported by the Result.getLastDocumentId() function. The example assumes that the test schema exists and is assigned to the variable db, that the collection my_collection exists and that custom_id is unique.

MySQL Shell JavaScript Code

// If the _id is provided, it will be honored
var result = myColl.add( { _id: 'custom_id', a : 1 } ).execute();
print("User Provided Id:", result.getLastDocumentId());

// If the _id is not provided, one will be automatically assigned
result = myColl.add( { b: 2 } ).execute();
print("Autogenerated Id:", result.getLastDocumentId());

MySQL Shell Python Code

# If the _id is provided, it will be honored
result = myColl.add( { '_id': 'custom_id', 'a' : 1 } ).execute()
print "User Provided Id: %s" % result.get_last_document_id()

# If the _id is not provided, one will be automatically assigned
result = myColl.add( { 'b': 2 } ).execute()
print "Autogenerated Id: %s" % result.get_last_document_id()

Node.js JavaScript Code

// If the _id is provided, it will be honored
myColl.add( { _id: 'custom_id', a : 1 } ).execute().then(function (result) {
    console.log("User Provided Id:", result.getLastDocumentId());
});

// If the _id is not provided, one will be automatically assigned
myColl.add( { b: 2 } ).execute().then(function(result) {
    console.log("Autogenerated Id:", result.getLastDocumentId());
});

C# Code

{
// If the _id is provided, it will be honored
var result = myColl.Add(new { _id = "custom_id", a = 1 }).Execute();
Console.WriteLine("User Provided Id:", result.AutoIncrementValue);

// If the _id is not provided, one will be automatically assigned
result = myColl.Add(new { b = 2 }).Execute();
Console.WriteLine("Autogenerated Id:", result.AutoIncrementValue);
}

Java Code

// If the _id is provided, it will be honored
Result result = coll.add("{\"_id\":\"custom_id\",\"a\":1}").execute();
System.out.println("User Provided Id:" + result.getLastDocumentIds().get(0));

// If the _id is not provided, one will be automatically assigned
result = coll.add("{\"b\":2}").execute();
System.out.println("Autogenerated Id:" + result.getLastDocumentIds().get(0));

C++ Code

// If the _id is provided, it will be honored
Result result = myColl.add(R"({ "_id": "custom_id", "a" : 1 })").execute();
cout << "User Provided Id:" << result.getDocumentId() << endl;

// If the _id is not provided, one will be automatically assigned
result = myColl.add(R"({ "b": 2 })").execute();
cout << "Autogenerated Id:" << result.getDocumentId()) << endl;

Some documents have a natural unique key. For example, a collection that holds a list of books is likely to include the International Standard Book Number (ISBN) for each document that represents a book. The ISBN is a string with a length of 13 characters which is well within the length limit of the _id field.

MySQL Shell JavaScript Code

// using a book's unique ISBN as the document ID
myColl.add( {
_id: "978-1449374020",
title: "MySQL Cookbook: Solutions for Database Developers and Administrators"
}).execute();

Use find() to fetch the newly inserted book from the collection by its document ID:

MySQL Shell JavaScript Code

var book = myColl.find('_id = "978-1449374020"').execute();

Currently, the X DevAPI does not support using any document field other than the implicit _id as the document ID. There is no way of defining a different document ID (primary key).

Collection.find()

The find() function is used to get documents from the database. It takes a SearchConditionStr as a parameter to specify the documents that should be returned from the database. Several methods such as fields(), sort(), skip() and limit() can be chained to the find() function to further refine the result.

The fetch() function actually triggers the execution of the operation. The example assumes that the test schema exists and that the collection my_collection exists.

MySQL Shell JavaScript Code

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

// Find a single document that has a field 'name' starts with an 'S'
var docs = myColl.find('name like :param').
           limit(1).bind('param', 'S%').execute();

print(docs.fetchOne());

// Get all documents with a field 'name' that starts with an 'S'
docs = myColl.find('name like :param').
        bind('param','S%').execute();

var myDoc;
while (myDoc = docs.fetchOne()) {
print(myDoc);
}

MySQL Shell Python Code

# Use the collection 'my_collection'
myColl = db.get_collection('my_collection')

# Find a single document that has a field 'name' starts with an 'S'
docs = myColl.find('name like :param').limit(1).bind('param', 'S%').execute()

print docs.fetch_one()

# Get all documents with a field 'name' that starts with an 'S'
docs = myColl.find('name like :param').bind('param','S%').execute()

myDoc = docs.fetch_one()
while myDoc:
  print myDoc
  myDoc = docs.fetch_one()

Node.js JavaScript Code

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

// Find a single document that has a field 'name' starts with an 'S'
myColl.find('name like :name').bind('S%').limit(1).execute(function (doc) {
  console.log(doc);
});

// Get all documents with a field 'name' that starts with an 'S'
myColl.find('name like :name')
.bind('S%').execute(function (myDoc) {
  console.log(myDoc);
});

C# Code

{
// Use the collection "my_collection"
var myColl = db.GetCollection("my_collection");

// Find a single document that has a field "name" starts with an "S"
var docs = myColl.Find("name like :param")
.Limit(1).Bind("param", "S%").Execute();

Console.WriteLine(docs.FetchOne());

// Get all documents with a field "name" that starts with an "S"
docs = myColl.Find("name like :param")
.Bind("param", "S%").Execute();

while (docs.Next())
{
Console.WriteLine(docs.Current);
}
}

Java Code

// Use the collection 'my_collection'
Collection myColl = db.getCollection("my_collection");

// Find a single document that has a field 'name' starts with an 'S'
DocResult docs = myColl.find("name like :name").bind("name", "S%").execute();

System.out.println(docs.fetchOne());

// Get all documents with a field 'name' that starts with an 'S'
docs = myColl.find("name like :name").bind("name", "S%").execute();

while (docs.hasNext()) {
    DbDoc myDoc = docs.next();
    System.out.println(myDoc);
}

C++ Code

// Use the collection 'my_collection'
Collection myColl = db.getCollection("my_collection");

// Find a single document that has a field 'name' starts with an 'S'
DocResult docs = myColl.find("name like :param")
                       .limit(1).bind("param", "S%").execute();

cout << docs.fetchOne() << endl;

// Get all documents with a field 'name' that starts with an 'S'
docs = myColl.find("name like :param")
             .bind("param","S%").execute();

DbDoc myDoc;
while ((myDoc = docs.fetchOne()))
{
  cout << myDoc << endl;
}

The following diagram shows the full syntax definition.

Figure 4.2 Collection.find() Syntax Diagram

Collection.find() Syntax Diagram

For more information, see Section 11.7, “Other EBNF Definitions”.

Collection.modify()

Figure 4.3 Collection.modify() Syntax Diagram

Collection.modify() Syntax Diagram

Collection.remove()

Figure 4.4 Collection.remove() Syntax Diagram

Collection.remove() Syntax Diagram


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