Skip to main content

Command Palette

Search for a command to run...

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

Published
2 min read

MongoDB is a powerful NoSQL database that allows you to store and retrieve data in a flexible and scalable way. In this guide, I’ll walk you through creating a new MongoDB database and collection, inserting multiple documents, and querying those documents using simple filters.

Step 1: Creating a MongoDB Database

To create a new database in MongoDB, you simply need to switch to a non-existing database, and it will automatically create it when you insert data.

use myDatabase

Step 2: Creating a Collection

Now, let’s create a collection in this database called users.

db.createCollection('users')

Step 3: Inserting Documents

You can now insert documents into the users collection. Let’s add a few sample records:

db.users.insertMany([
    { "name": "John Doe", "age": 28, "city": "New York" },
    { "name": "Jane Smith", "age": 32, "city": "Los Angeles" },
    { "name": "Sam Wilson", "age": 25, "city": "Chicago" },
    { "name": "Sara Lee", "age": 29, "city": "San Francisco" },
    { "name": "Mike Jordan", "age": 35, "city": "Miami" }
])

Step 4: Querying Documents with Filters

MongoDB provides powerful querying capabilities. Here are some examples:

  • Find users by city:

      db.users.find({ "city": "New York" })
    
  • Find users aged above 30:

      db.users.find({ "age": { $gt: 30 } })
    
  • Find users by age range:

      db.users.find({ "age": { $gte: 25, $lte: 30 } })
    

Conclusion

That’s it! You’ve created a MongoDB database, inserted documents, and learned how to use filters to query data. MongoDB’s flexible schema allows you to store diverse types of data, making it a great choice for modern applications.


More from this blog

Amazon S3 Storage Classes

43 posts