MongoDB is a popular NoSQL database that is widely used in modern web development. TypeScript, on the other hand, is a popular programming language that is gaining popularity in the web development community because of its static typing and improved error checking. In this tutorial, we will learn how to query MongoDB with TypeScript.

Prerequisites

Before we get started, make sure that you have the following installed on your system:

  • Node.js
  • MongoDB
  • TypeScript

You should also have a basic understanding of TypeScript and MongoDB.


Getting Started

To get started, create a new directory for your project and navigate to it in your terminal. Then, create a new package.json file by running the following command:

npm init -y

Next, install the necessary dependencies:

npm install mongodb @types/mongodb

This will install the MongoDB driver for Node.js and the TypeScript type definitions for the driver.


Connecting to MongoDB

The first step to querying MongoDB with TypeScript is to connect to the database. To do this, create a new TypeScript file called index.ts and add the following code:

import { MongoClient } from 'mongodb';

const url = 'mongodb://localhost:27017';
const dbName = 'my-database';

async function main() {
  const client = await MongoClient.connect(url);
  const db = client.db(dbName);
  console.log('Connected to MongoDB');
  
  // Use the db object to perform queries
  // ...
  
  client.close();
}

main();

This code connects to the MongoDB server running on localhost and port 27017 and selects the my-database database. The main function logs a message to the console to confirm that the connection was successful.


Performing Queries

Now that we have connected to the database, we can perform queries. Here are some examples:

// Insert a document
const result = await db.collection('my-collection').insertOne({ name: 'Alice', age: 30 });
console.log(`Inserted document with _id: ${result.insertedId}`);

// Find documents
const cursor = db.collection('my-collection').find({ age: { $gt: 25 } });
await cursor.forEach((doc) => {
  console.log(doc);
});

// Update documents
const updateResult = await db.collection('my-collection').updateOne({ name: 'Alice' }, { $set: { age: 31 } });
console.log(`Updated ${updateResult.modifiedCount} document(s)`);

// Delete documents
const deleteResult = await db.collection('my-collection').deleteOne({ name: 'Alice' });
console.log(`Deleted ${deleteResult.deletedCount} document(s)`);


The first example inserts a document into a collection called my-collection. The insertOne method returns an object containing the _id of the newly inserted document.

The second example finds documents in my-collection where the age field is greater than 25. The find method returns a cursor, which we can use to iterate over the results. In this case, we use the forEach method to log each document to the console.

The third example updates a document in my-collection where the name field is Alice. The updateOne method takes two arguments: a filter object that specifies which documents to update, and an update object that specifies how to update the documents.

The fourth example deletes a document from my-collection where the name field is Alice. The deleteOne method returns an object containing the number of documents that were deleted.

Conclusion

In this tutorial, we learned how to query MongoDB with TypeScript. We started by connecting to the database and then performed some common query operations such as inserting, finding, updating, and deleting documents. With this knowledge, you can now build powerful web applications using TypeScript and MongoDB.

Of course, this is just the beginning. MongoDB has many more advanced features, and TypeScript has many more powerful language constructs that you can use to make your code more expressive and maintainable. But with the fundamentals in place, you can confidently explore these features on your own.

As a final note, it's worth mentioning that TypeScript has a number of powerful features that can help you write more robust and maintainable code. For example, you can use interfaces to define the structure of your documents, and you can use enums to define constants that are used throughout your code. TypeScript also supports advanced language features like async/await and generators, which can make it easier to write asynchronous code.

So if you're interested in building powerful web applications with TypeScript and MongoDB, there's never been a better time to get started. With the right tools and a little bit of practice, you can create applications that are both powerful and maintainable, and that will stand the test of time.