Getting Started with MongoDB: Creating a Database, Collection, and Querying Documents

Ayushmaan Srivastav
2 min readOct 17, 2024

--

Introduction

MongoDB is a powerful NoSQL database that provides flexibility and scalability for modern applications. In this blog post, we’ll walk through the process of creating a new MongoDB database and collection, inserting several documents, and querying them using filters.

Prerequisites

  • Basic understanding of NoSQL databases and MongoDB.
  • MongoDB installed on your machine or access to a MongoDB cloud service (like MongoDB Atlas).
  • MongoDB client, such as MongoDB Compass or the command-line interface.

Step 1: Create a New MongoDB Database and Collection

Connecting to MongoDB

To start, connect to your MongoDB server using the MongoDB shell or a MongoDB client. If you’re using the shell, you can connect by running:

mongo

Create a New Database

Once connected, create a new database named my_database:

use my_database

Create a New Collection

Next, create a new collection called users:

db.createCollection("users")

Step 2: Insert Several Documents

Now that we have our collection, let’s insert several user documents with attributes such as name, age, city, and email.

Inserting Documents

You can insert multiple documents using the insertMany method. Here’s how to do it:

db.users.insertMany([
{ name: "Alice", age: 28, city: "New York", email: "alice@example.com" },
{ name: "Bob", age: 34, city: "Los Angeles", email: "bob@example.com" },
{ name: "Charlie", age: 22, city: "Chicago", email: "charlie@example.com" },
{ name: "Diana", age: 29, city: "New York", email: "diana@example.com" },
{ name: "Ethan", age: 42, city: "Los Angeles", email: "ethan@example.com" }
]);

Step 3: Querying Documents Using Filters

Now that we have inserted documents, we can query them using various filters.

Query by Age

To find users by age, you can use the find method with a filter. For example, to find users who are 28 years old:

db.users.find({ age: 28 }).pretty()

Query by City

To find users who live in Los Angeles, you can use:

db.users.find({ city: "Los Angeles" }).pretty()

Step 4: Using Complex Queries

MongoDB allows for more complex queries as well. For instance, if you want to find users who are older than 30:

db.users.find({ age: { $gt: 30 } }).pretty()

Step 5: Retrieve Specific Fields

If you want to retrieve only specific fields (e.g., name and email), you can do so by specifying the fields in the find method:

db.users.find({}, { name: 1, email: 1, _id: 0 }).pretty()

Conclusion

In this blog post, we explored how to create a new MongoDB database and collection, insert several documents, and query them using filters. MongoDB’s flexible schema and powerful querying capabilities make it an excellent choice for modern applications.

--

--

No responses yet