Technology Sharing

MongoDB: Master the core common commands and be proficient in data operations

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

title:MongoDB: Master core commands and be proficient in data operations

Preface:

MongoDB is aNon-relational database, is document-centric and uses BSON in JSON format to store data. It has the characteristics of high availability, high performance and easy scalability, and is widely used in projects of all sizes. This article will introduce the common commands of MongoDB in detail to help you better understand and master MongoDB data operations.

1. Connection and Disconnectiondatabase

To start using MongoDB, you first need to connect to the database. Enter the following command in the command line:

mongo
  • 1

This will connect to the MongoDB server running locally. If your server is running at a different location or port, you can use the following format:

mongo [host]:[port]
  • 1

For example:

mongo localhost:27017
  • 1

Once connected, you can use use The command switches to the specified database:

use [database_name]
  • 1

If the database does not exist, MongoDB will automatically create a new database. To disconnect from MongoDB, simply type exit orquit Just run the command.

2. Insert data

MongoDB usage insertOne() andinsertMany() Method to insert data. The following is an example of inserting a single document:

db.collection.insertOne({ name: "John", age: 3