Data Definition

Data definition involves creating, altering, and dropping namespaces and collections. This section will guide you through these crucial operations.

Creating Namespaces and Collections

Namespaces are created implicitly upon their first use. For instance, if you execute a write operation after selecting a namespace that does not exist, Polypheny will create that namespace for you.

For collections, you can create them explicitly using the createCollection() method:

db.createCollection( 'users' )

This command creates a new collection named users. If the collection already exists, MongoDB will return an error.

Rename Collections

To rename a collection use the following command:

db.users.renameCollection( 'customers', dropTarget )

dropTarget is a optional boolean. If true, an existing collection with the target name (‘customers’ in the example above) will be deleted prior to the rename operation. The default value is false.

The operation fails if there is already a collection with this name, and dropTarget is false.

Dropping Namespaces and Collections

To delete a namespace in Polypheny, you can use the dropDatabase() command. Be careful with this command as it permanently deletes the entire namespace including all entities and data:

db.dropDatabase()

The dropDatabase() command operates on the currently selected namespace.

To delete a collection, you can use the drop() command:

db.users.drop()

This command deletes the users collection.

Views

A view in the document model is a result set which behaves much like a virtual collection. You can create, modify, and drop views in Polypheny using MQL commands.

Views are created using the db.createView() method. The method takes three arguments: the name of the view, the source collection, and an array of aggregation pipeline stages. Here’s an example:

db.createView(
   "user_view",
   "users",
   [
     { $match: { age: { $gte: 18 } } },
     { $project: { _id: 0, name: 1, email: 1 } }
   ]
)

This command creates a view named user_view based on the users collection. The view includes documents that match the $match stage (users aged 18 and older), and the $project stage specifies that only the name and email fields should be included in the view.

You can drop a view just like you drop a collection, using the drop() method:

db.user_view.drop()

This command drops the user_view view.

Index Management

Indexes support efficient execution of queries and are crucial for performance optimization. To create an index, use the createIndex() method:

db.collection.createIndex( { "username" : 1 } )

This command creates an index on the username field in ascending order (1 signifies ascending order, -1 would be descending).

To delete an index, use the dropIndex() method:

db.collection.dropIndex( "username_1" )

This command deletes the index named username_1.

© Polypheny GmbH. All Rights Reserved.