Documentation Home
X DevAPI User Guide
Download this Manual

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

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.

If the collection does not yet exist in the database, any subsequent call of a Collection object function throws an error; for some of the Connectors, you can prevent that and catch the error right at the time of Collection retrival by setting the validateExistence field to true and pass it as second parameter to db.getCollection().

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 collection = db.getCollection('my_collection');

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);

Python Code

# Get a collection object for 'my_collection'
my_coll = my_schema.get_collection('my_collection')
# Get a collection object but also ensure it exists in the database
my_coll = my_schema.get_collection('my_collection', 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);

The createCollection(), together with the ReuseExistingObject field set to true, can be used to create a new collection or reuse an existing collection with the given name. See Section 4.2.1, “Creating a Collection” for details.

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.