Documentation Home
X DevAPI User Guide
Download this Manual
PDF (US Ltr) - 1.0Mb
PDF (A4) - 1.0Mb
EPUB - 0.7Mb
HTML Download (TGZ) - 0.6Mb
HTML Download (Zip) - 0.7Mb


X DevAPI User Guide  /  ...  /  Working with Existing Collections

Beta Draft: 2017-03-17

4.2.2 Working with Existing Collections

In order to retrieve a Collection object for an existing collection stored in the database call the getCollection() function from a Schema object.

MySQL Shell JavaScript Code

// Get a collection object for 'my_collection'
var myColl = db.getCollection('my_collection');

MySQL Shell Python Code

# Get a collection object for 'my_collection'
myColl = db.get_collection('my_collection')

Node.js JavaScript Code

// Get a collection object for 'my_collection'
var promise = db.getCollection('my_collection');

// Get a collection object but also ensure it exists in the database
var promise = db.getCollection('my_collection', { validateExistence: true } );

C# Code

{
  // Get a collection object for "my_collection"
  var myColl = db.GetCollection("my_collection");

  // Get a collection object but also ensure it exists in the database
  var myColl2 = db.GetCollection("my_collection", ValidateExistence: true);
}

Java Code

// Get a collection object for 'my_collection'
Collection myColl = db.getCollection("my_collection");

// Get a collection object but also ensure it exists in the database
// second parameter is: boolean requireExists
Collection myColl = db.getCollection("my_collection", true);

C++ Code

// Get a collection object for 'my_collection'
Collection myColl = db.getCollection("my_collection");

// Get a collection object but also ensure it exists in the database
Collection myColl = db.getCollection("my_collection", true);

If the collection does not yet exist in the database any subsequent call of a Collection object function throws an error. To prevent this and catch the error right away set the validateExistence field to true and pass it as second parameter to db.getCollection().

The createCollection() together with the ReuseExistingObject field set to true can be used to create a new or reuse an existing collection with the given name.

Note

In most cases it is good practice to create database objects during development time and refrain from creating them on the fly during the production phase of a database project. Therefore it is best to separate the code that creates the collections in the database from the actual user application code.


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