Introduction
MongoDB is a popular NoSQL database system that stores data in a JSON-like format called BSON (Binary JSON). MongoDB Server is the core component of MongoDB, responsible for managing data storage, retrieval, and processing. In this documentation, we will cover the installation, basic usage, and code examples for working with MongoDB Server.
Installation
MongoDB Server can be installed on various operating systems. Here, we'll provide installation instructions for Ubuntu Linux:
- Add the MongoDB repository:
bash$ wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -
$ echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu $(lsb_release -cs)/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list
$ sudo apt-get update
- Install MongoDB Server:
bash$ sudo apt-get install -y mongodb-org
- Start and enable MongoDB:
bash$ sudo systemctl start mongod
$ sudo systemctl enable mongod
Basic Usage
MongoDB Server can be interacted with using its official shell, which is a JavaScript-based interface. Here are some common commands:
- Connect to MongoDB Shell
bash$ mongo
- Show Databases
javascript> show dbs
- Switch/Use a Database
javascript> use mydatabase
- Create a Collection
javascript> db.createCollection("mycollection")
- Insert a Document
javascript> db.mycollection.insertOne({ name: "John Doe", age: 30, email: "john@example.com" })
- Find Documents
javascript> db.mycollection.find({ age: { $gt: 25 } })
- Update Documents
javascript> db.mycollection.updateOne({ name: "John Doe" }, { $set: { age: 31 } })
- Delete Documents
javascript> db.mycollection.deleteOne({ name: "John Doe" })
Explanation of Code Examples
We start by connecting to the MongoDB shell using the
mongo
command. It opens up a JavaScript-based shell to interact with the database.show dbs
displays all the available databases on the MongoDB server.use mydatabase
switches to the specified database (replacemydatabase
with the desired database name).db.createCollection("mycollection")
creates a new collection namedmycollection
in the current database.db.mycollection.insertOne({ name: "John Doe", age: 30, email: "john@example.com" })
inserts a document into themycollection
collection.db.mycollection.find({ age: { $gt: 25 } })
searches and retrieves documents from the collection where the age is greater than 25.db.mycollection.updateOne({ name: "John Doe" }, { $set: { age: 31 } })
updates the age of the document with the name "John Doe" to 31.db.mycollection.deleteOne({ name: "John Doe" })
deletes the document with the name "John Doe" from the collection.
Remember that MongoDB offers a lot more functionalities, such as indexing, aggregation, and data replication, which are essential for real-world applications. The examples provided here are basic to give you a starting point for working with MongoDB Server.
0 Comments