2

Up and Running with MongoDB

 2 years ago
source link: https://blog.bitsrc.io/mongodb-the-only-database-you-need-15795b9f4040
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Up and Running with MongoDB

An introduction to MongoDB: the only NoSQL database you’ll need

Photo by Christina Morillo from Pexels

MongoDB is a NoSQL document-based database. Essentially, all the data in MongoDB is stored in JSON documents that are sorted into a variety of collections based on the type of data. It is the most popular NoSQL database, at present.

Getting Started

MongoDB can be used online using Atlas or we can download MongoDB to our system. I prefer using Atlas since it's more comfortable to use with the help of Mongoose. The first thing we need to do is include Mongoose in our project and open a connection to our test database on our instance of MongoDB.

Some terms you should know

MongoDB is different from a SQL database which consists of rows, columns, and fields.

So let’s learn some MongoDB jargon:

1. Database

A database is simply a container for collections. A database in MongoDB is the same conceptually as a database in SQL and usually, a project will have one database full of different collections.

2. Collection

A collection is a grouping of documents inside a database. This is the same conceptually as tables in a SQL database.

3. Document

A document generally represents one single object within a collection. In MongoDB, a document is essentially just a JSON object.

Next, let's look at the Create, Read, Update, Delete methods we will use whenever we want to interact with our database.

Create

Creating documents in MongoDB is actually pretty simple since there are only two methods to do so and they both are very similar.

insertOne This function takes a single object and creates a document with the specified information within the specified collection.

db.users.insertOne({ name: "AdarshGupta" })

insertMany This function works just like insertOne, but it takes an array of objects to be inserted instead.

db.users.insertMany([{ age: 19 }, { name: "Adarsh Gupta" }])

Reading data within MongoDB is much more complicated and is where some confusion around MongoDB can arise.

If you want to get all the documents within a single collection you can use the find method with no additional parameters.

// Get all the users.
db.users.find()

You can pass an object as a parameter to the find() method and it will return documents that match all the fields in the filter. The object can have multiple values, too.

// Get all users with the name Kyle
db.users.find({ name: "John Cena" })

// Get all users whose address field has a zip field with the value 678599
db.users.find({ "address.zip": "678599" })`

The final way to use the find method is by passing a second object to select which fields you want to be returned — find(<filterObject>, <selectObject>). The object contains a key which is the field and a value of either 0 or 1 to determine if that field is returned or not. By default, the _id property is always returned unless specifically told not.

// Get all users with the name Elon and return the name, age, and _id fields
db.users.find({ name: "Elon" }, { name: 1, age: 1})

// Get all users and return all fields except the age field
db.users.find({}, { age: 0 })

There is also findOne, which is the same as find in every way except it just returns the first document that matches the filter.

// Get the first user with the name Rey Misterio
db.users.findOne({ name: "Rey Misterio" })

Update

Updating documents in MongoDB is a bit more complex than in SQL since there are actually many different ways you can update a document.

The updateOne() method will update the first document that matches the filter passed to it and will then update the document based on the information passed in the second parameter to updateOne.

// Update the age of the first user with an age of 45 to 55
db.users.updateOne({ age: 45 }, { $set: { age: 50 } })

The updateMany() method works exactly the same as updateOne, but it will update all documents that match the filter object instead of just the first.

The replaceOne() method works similarly to updateOne, but it will instead replace the entire document and not just update specific fields.

// Replace the first user with an age of 20 with an object that only has a name field 
db.users.replaceOne({ age: 20}, { name: "Adarsh" })

Delete

The deleteOne() method will delete the first object that matches the filter object passed to it.

db.users.deleteOne({ age: 20 }) 

deleteMany This is the same as deleteOne but it will delete all documents that match the filter object instead of just one.

db.users.deleteMany({ age: 14 })

Conclusion

Here we have learned the main topics related to MongoDB. We have covered all the main MongoDB concepts that are Create, Read, Update, Delete, which is usually enough to get you up and running with a MongoDB database.

If you are interested in learning more about MongoDB, you can check out myfree MongoDB cheatsheet.

References:

MongoDB https://www.mongodb.com/

Mongoose https://mongoosejs.com/

Thank you for reading. I hope you have found this useful!

Unlock 10x development with independent components

Building monolithic apps means all your code is internal and is not useful anywhere else. It just serves this one project. And as you scale to more code and people, development becomes slow and painful as everyone works in one codebase and on the same version.

But what if you build independent components first, and then use them to build any number of projects? You could accelerate and scale modern development 10x.

OSS Tools like Bit offer a powerful developer experience for building independent components and composing modular applications. Many teams start by building their Design Systems or Micro Frontends, through independent components. Give it a try →

0*-Bqif4OccFAwgECn?q=20
mongodb-the-only-database-you-need-15795b9f4040
An independent product component: watch the auto-generated dependency graph

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK