Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Thursday 22 February 2024

Create Table As in MongoDB

In MongoDB, there isn't a direct equivalent of the CREATE TABLE AS statement found in traditional relational databases. However, you can achieve similar functionality using MongoDB's aggregation framework and the $out stage.


Here's how you can create a new collection based on the result set of a query in MongoDB:


db.sourceCollection.aggregate([

    { $match: { salary: { $gt: 100000 } } }, // Filter documents

    { $project: { employee_id: 1, first_name: 1, last_name: 1, salary: 1, department_id: 1 } }, // Select fields

    { $out: "high_salary_employees" } // Save results to a new collection

])


In this example:

- sourceCollection is the name of the collection you want to query.

- $match stage filters documents based on the specified condition (salary greater than $100,000).

- $project stage selects the fields you want to include in the new collection.

- $out stage specifies the name of the new collection where the results will be stored (in this case, "high_salary_employees").


This aggregation pipeline will process documents from the sourceCollection, apply the specified filters and projections, and then store the results in a new collection called high_salary_employees.


It's important to note that:


1. The $out stage will replace any existing collection with the same name. If the collection doesn't exist, MongoDB will create it.

2. The new collection will not inherit any indexes or other properties from the original collection. You may need to create indexes or other configurations on the new collection as needed.

3. The aggregation pipeline can be quite powerful, allowing for complex data transformations and computations before storing the results in a new collection.


Keep in mind that this approach is more aligned with MongoDB's document-oriented paradigm rather than the table-based paradigm of traditional relational databases.

No comments:

Post a Comment

Please provide your feedback in the comments section above. Please don't forget to follow.