Getting started with MongoDB

  • avatar
  • 722 Views
  • 6 Likes
  • 11 mins read

MongoDB is a popular open source and document oriented database system. It belongs to a family of databases called NoSQL, which is different from the traditional table based SQL databases. It makes use of collections, each having multiple documents, and allows the user to store data in a non relational format. Data is stored in flexible, JSON-like documents where fields can vary from document to document. That's the reason for calling it schemaless database.

MongoDB is highly scalable and flexible. It is used for building modern applications that require powerful, mission critical and high availability databases.

Prerequisites

Before proceeding with this tutorial, we should have a basic understanding of concepts commonly used in MongoDB. You will find these words in your daily routine working with it:

  • Document - a way to organize and store data as a set of field-value pairs.

  • Field - a unique identifier for a datapoint containing some value.

  • Collection - an organized store of documents, usually with common fields between documents. There can be many collections per database and many documents per collection.

  • Replica Set - a few connected machines that store the same data to ensure that if something happens to one of the machines the data will remain intact. Comes from the word replicate - to copy something.

  • Instance - a single machine locally or in the cloud, running a certain software, in our case it is the MongoDB database.

  • Cluster - group of servers that store your data.

  • Namespace - The concatenation of the database name and collection name is called a namespace.

  • JSON - JavaScript Standard Object Notation

  • BSON - Binary JSON (binary encoding and machine only readability). Data in MongoDB in stored in BSON but viewed in JSON.

You will need a running MongoDB server. If you don't have one check on how to install MongoDB 6.

Getting Started

This tutorial walks you through inserting test data into a MongoDB database and querying that data. After completing the tutorial, you will have a basic understanding of MongoDB and how to use the mongo shell to interact with the MongoDB database server.

Creating database

After connecting to your database using mongosh, you can see which database you are using by typing db in your terminal. You can see all the databases in the cluster that you have access to using the show command:

> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB

Note: admin and local are databases that are part of every MongoDB cluster.

In order to create a database, you will first need to switch the context to a non-existing database:

> use hibit
switched to db hibit

For now, only the context has been changed. MongoDB creates the database when you first store data in that database. This data could be a collection or a document.

Creating collection

You can create a new collection using the createCollection function. The server will acknowledge with the following response:

> db.createCollection("users")
{ "ok" : 1 }

As we have a collection in our recently created database, now we will be able to see it in the databases list:

> show dbs
admin 0.000GB
config 0.000GB
hibit 0.000GB
local 0.000GB
test 0.000GB

Inserting documents

Every document have one thing in common, all of them must have an _id field that acts as a primary key. Therefore, every id field in a collection must have a unique value. ObjectId is the default value for the _id field unless otherwise is specified. In order to generate a new id run the function in MongoDB shell:

> ObjectId()
ObjectId("635d69895c37db05ae1c892e")

It returns 12-byte ObjectId value that consists of:

  • 4-byte timestamp, representing the ObjectId's creation, measured in seconds since the Unix epoch.

  • 5-byte randomly generated once per process. This random value is unique to the machine and process.

  • 3-byte incrementing counter, initialized to a random value.

There are no restrictions on the document, besides the id, while we use JSON. We can have identical documents with different id fields. Or the opposite, have totally different documents with different id fields. However, it's not good practice nor a good way to organize the data. We should follow good practices with data modeling to take full advantage from MongoDB.

The command schema to insert a document:

db.collection.insert(<document or array of documents>, {ordered: <boolean>})
  • ordered: optional, defaults to true.

    • If true, perform an ordered insert of the documents in the array, and if an error occurs with one of documents, MongoDB will return without processing the remaining documents in the array.

    • If false, perform an unordered insert, and if an error occurs with one of documents, continue processing the remaining documents in the array.

An example of inserting two documents in users collection.

> db.users.insert([
{ "_id": 1, "name": "Bob", "surname": "Smith", "age": 30 },
{ "_id": 2, "name": "Bob", "surname": "Brown", "age": 40 }
])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})

If a document is inserted without a provided id value, then the id field and value will be automatically generated for the inserted document before insertion.

> db.users.insert([
{ "name": "John", "surname": "Smith", "age": 30 },
{ "name": "John", "surname": "Brown", "age": 40 }
])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})

Reading documents

To locate data from a collection in we use the find function. The command schema to find a document:

db.collection.find(<query>, <projection>)
  • query: optional, specifies the criteria using query operators.

  • projection: optional, specifies the fields to include in a resulted document.

The findOne function works in the same way but returns the first document from a collection with the specified criteria. Take into consideration that filters are concatenated using AND operator.

{ "field1": "value", "field2": "value", ... }

For example, the following returns a document where name field is John.

> db.users.find({"name": "John"})
{ "_id" : ObjectId("635d6b9c5c37db05ae1c8931"), "name" : "John", "surname" : "Smith", "age" : 30 }
{ "_id" : ObjectId("635d6b9c5c37db05ae1c8932"), "name" : "John", "surname" : "Brown", "age" : 40 }

To prettify the JSON response for the same query use pretty function.

> db.users.find({"name": "John"}).pretty()
{
"_id" : ObjectId("635d6b9c5c37db05ae1c8931"),
"name" : "John",
"surname" : "Smith",
"age" : 30
}
{
"_id" : ObjectId("635d6b9c5c37db05ae1c8932"),
"name" : "John",
"surname" : "Brown",
"age" : 40
}

If the amount of results is paginated we can iterated through using it command. And, to know the exact number of documents that match the find query we use count function.

> db.users.find({"name": "John"}).count()
2

In the same way we can filter by the ID value:

> db.users.find({ "_id": 1 })
{ "_id" : 1, "name" : "Bob", "surname" : "Smith", "age" : 30 }

Both find functions accept a second parameter called projection. This parameter is an object that describes which fields to include or exclude from the results. We use a 1 to include a field and 0 to exclude a field.

> db.users.find({ "_id": 1 }, { "_id": 1, "name": 1, "surname": 1, "age": 1 })
{ "_id" : 1, "name" : "Bob", "surname" : "Smith", "age" : 30 }

You cannot use inclusion and exclusion in the same object. The only exception is the _id field. You should either specify the fields you would like to include or the fields you would like to exclude.

Updating documents

MongoDB provides two functions to update existing documents in a collection. The command schema to modify a single document in a collection that match a given query and to modify all documents in a collection that match a given query:

db.collection.updateOne(<filter>, <update>, <options>)
db.collection.updateMany(<filter>, <update>, <options>)
  • filter: specifies the criteria using query operators.

  • update: document or pipeline that contains modifications to apply.

  • options: optional, specifies additional options for update behavior.

Update a single document in the users collection where the age field is equal to 30 by setting it to 50.

> db.users.updateOne({ "age": 30 }, { "$set": { "age": 30 } })
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 }

Update all documents in users collection where the name field is John by adding 1 to the current value of the age field.

> db.users.updateMany({ "name": "John" }, { "$inc": { "age": 1 } })
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }

Update one document in users collection where the name field is Bob, and surname is Smith, by pushing an element to the interests array.

> db.users.updateOne({ "name": "Bob", "surname": "Smith" }, { "$push": { "interests": "programming" } })
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

It will append to the interests array a new interest:

> db.users.find({ "name": "Bob", "surname": "Smith" })
{ "_id" : 1, "name" : "Bob", "surname" : "Smith", "age" : 30, "interests" : [ "programming" ] }

The full list of update operators is available in the official documentation.

In MongoDB, you can perform document updates using the upsert option. The term upsert denotes an operation that either updates an existing document based on specific criteria or inserts a new document if no matching one is present. Here's an example of a query with the upsert option:

> db.users.updateOne({ "age": 30 }, { "$set": { "age": 30 } }, { "upsert": true })

Make sure to use it carefully, only when it's necessary.

Deleting documents

MongoDB provides two functions to delete existing documents from a collection. The command schema to delete a single document from a collection that match a given query and to delete all documents in a collection that match a given query:

db.collection.deleteOne(<filter>, <options>)
db.collection.deleteMany(<filter>, <options>)
  • filter: specifies the criteria using query operators.

  • options: optional, specifies additional options for delete behavior.

Delete all the documents that have name field equal to John.

> db.users.deleteMany({ "name": "John" })
{ "acknowledged" : true, "deletedCount" : 2 }

Delete one document that has surname field equal to Brown.

> db.users.deleteOne({ "surname": "Brown" })
{ "acknowledged" : true, "deletedCount" : 1 }

To drop users collection:

> db.users.drop()
true

Conclusion

This can be a good point to get started with MongoDB. A good base will allow you to easily improve your NoSQL skills and continue with advanced query commands.

 Join Our Monthly Newsletter

Get the latest news and popular articles to your inbox every month

We never send SPAM nor unsolicited emails

0 Comments

Leave a Reply

Your email address will not be published.

Replying to the message: View original

Hey visitor! Unlock access to featured articles, remove ads and much more - it's free.