Home Backend Development PHP Tutorial Summary of MongoDB tips and precautions

Summary of MongoDB tips and precautions

Dec 01, 2017 am 11:28 AM

Mongodb, a distributed document storage database, written in C++ language, aims to provide scalable, high-performance data storage solutions for WEB applications. MongoDB is a high-performance, open source, schema-less document database, which is currently a popular NoSQL database. This article will share with you the solving techniques for problems encountered when using MongoDB, and share them for your reference and learning.

1. Find records whose array fields are not empty

Find records whose array fields are not empty in the data.

For example: There is the following Mongo document,

{
 "id" : "581c060f2b436c05aafb1632",
 "commit_history" : [ 
 "581c20d52b436c05aafb1633", 
 "581c21c12b436c05aafb1634"
 ]
},
{
 "id" : "581c060f2b436c05aafb1633",
 "commit_history" : []
}
Copy after login

If you want to find records whose commit_history is not empty, there are the following methods:

Method 1: db.collection.find ({commit_history: {$not: {$size: 0}}})

Method 2: db.collection.find({'commit_history.0': {$exists: 1}})

2. Add a user to MongoDB

To add a user to a Collection in MongoDB, you can do the following:

use collection_name to switch to a library

db.createUser(
 {
 user: "collection_name",
 pwd: "password",
 roles: [ "readWrite", "dbAdmin" ]
 }
)
Copy after login

3. Sometimes it is necessary to delete the column of the specified field and use the update operation.

For example, to delete the name column:

query json:

{"name":{$exists:true}}
Copy after login

update json:

{$unset:{"name":""}}
Copy after login

4. Data export, in mongodb Execute the mongoexport command in the bin directory and set the relevant parameters

For example:

./mongoexport -h 192.168.0.201 --port 27017 –d admin –u admin –p admin -c department -o /home/admin/department.dat
Copy after login

-h: Specify the IP address of the database to be connected;

--port: Specify the database to be connected The port of the database;

-u: Specify the user name of the database to be connected;

-p: Specify the user password of the database to be connected;

-d: Specify the library name to be connected;

-c: Specify the data collection to be exported;

-o: Specify the target storage address of the data to be exported;

Note: (1) It is necessary to ensure that the connected database is in normal operation;

           (2) I once encountered a situation where user information was added to the database and it was not started with user authentication when starting. However, when executing this command, it was only after I specified the user name and password. The export was successful. If anyone encounters a similar situation, you might as well give it a try.

5. Data import, execute the mongoimport command in the bin directory of mongodb and set the relevant parameters. The parameter explanation is the same as above

For example:

./mongoimport --port 27017 -d admin -u admin –p admin –c department /home/common/mongodb305/bin/department.dat
Copy after login


6. User verification issues for non-amdin databases:

We add users to the library in the mongodb database. You can use the following commands in the target database, for example, add a user in the mongoTest library. Users with read and write permissions:

db.createUser({"user":"test","pwd":"123456","roles":["readWrite"]})
Copy after login


can also be added in the admin database:

db.createUser({"user":"test","pwd":"123456","roles":[{"role":"readWrite","db":"test"},"readWrite"]})
Copy after login


It should be noted that : There is a difference between these two methods, and it is this difference that once fooled me:

When using the first method to add, we can directly execute the following command in the bin directory of mongodb to enter. You can operate in the test database, add, delete, modify or check; you can also use this user The name and password are connected in mongoVUE:

./mongo -h 192.168.0.201 --port 27017 -u test -p 123456 -d test
Copy after login


But if it is created in the second way, then directly using the above command, it will prompt that the verification failed. Only when entering mongo first The shell is connected to the admin database, and then the verification can be passed when switching to the test database. This is a small pitfall. Those who don’t know the situation may be very confused. It is clear that the username and password are fine, but they don’t know why they can’t connect.

7. The default data storage method of mongodb3.0 is still the same as that of mongodb 2.6. I have tried changing to the new storage method and using the following parameters at startup. However, it should be noted that there needs to be no data in the database. This is only possible if the data is required, otherwise an error will be reported:

./mongod -f /mongodb304/conf/mongodb.conf --storageEngine wiredTiger
Copy after login

mongodb.conf is configured with various other parameters for startup, such as dbpath, logpath, etc.

The above content is a summary of the tips and precautions for daily use of MongoDB. I hope it can help everyone.

Related recommendations:

What is mongoDB database

How does phpstudy extend MongoDB

How to improve the security of MongoDB

The above is the detailed content of Summary of MongoDB tips and precautions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Apr 18, 2025 am 11:48 AM

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

How to choose a database for GitLab on CentOS How to choose a database for GitLab on CentOS Apr 14, 2025 pm 04:48 PM

GitLab Database Deployment Guide on CentOS System Selecting the right database is a key step in successfully deploying GitLab. GitLab is compatible with a variety of databases, including MySQL, PostgreSQL, and MongoDB. This article will explain in detail how to select and configure these databases. Database selection recommendation MySQL: a widely used relational database management system (RDBMS), with stable performance and suitable for most GitLab deployment scenarios. PostgreSQL: Powerful open source RDBMS, supports complex queries and advanced features, suitable for handling large data sets. MongoDB: Popular NoSQL database, good at handling sea

What is the CentOS MongoDB backup strategy? What is the CentOS MongoDB backup strategy? Apr 14, 2025 pm 04:51 PM

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

How to set up users in mongodb How to set up users in mongodb Apr 12, 2025 am 08:51 AM

To set up a MongoDB user, follow these steps: 1. Connect to the server and create an administrator user. 2. Create a database to grant users access. 3. Use the createUser command to create a user and specify their role and database access rights. 4. Use the getUsers command to check the created user. 5. Optionally set other permissions or grant users permissions to a specific collection.

How to encrypt data in Debian MongoDB How to encrypt data in Debian MongoDB Apr 12, 2025 pm 08:03 PM

Encrypting MongoDB database on a Debian system requires following the following steps: Step 1: Install MongoDB First, make sure your Debian system has MongoDB installed. If not, please refer to the official MongoDB document for installation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/Step 2: Generate the encryption key file Create a file containing the encryption key and set the correct permissions: ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512

MongoDB vs. Oracle: Choosing the Right Database for Your Needs MongoDB vs. Oracle: Choosing the Right Database for Your Needs Apr 22, 2025 am 12:10 AM

MongoDB is suitable for unstructured data and high scalability requirements, while Oracle is suitable for scenarios that require strict data consistency. 1.MongoDB flexibly stores data in different structures, suitable for social media and the Internet of Things. 2. Oracle structured data model ensures data integrity and is suitable for financial transactions. 3.MongoDB scales horizontally through shards, and Oracle scales vertically through RAC. 4.MongoDB has low maintenance costs, while Oracle has high maintenance costs but is fully supported.

What are the tools to connect to mongodb What are the tools to connect to mongodb Apr 12, 2025 am 06:51 AM

The main tools for connecting to MongoDB are: 1. MongoDB Shell, suitable for quickly viewing data and performing simple operations; 2. Programming language drivers (such as PyMongo, MongoDB Java Driver, MongoDB Node.js Driver), suitable for application development, but you need to master the usage methods; 3. GUI tools (such as Robo 3T, Compass) provide a graphical interface for beginners and quick data viewing. When selecting tools, you need to consider application scenarios and technology stacks, and pay attention to connection string configuration, permission management and performance optimization, such as using connection pools and indexes.

How to start mongodb How to start mongodb Apr 12, 2025 am 08:39 AM

To start the MongoDB server: On a Unix system, run the mongod command. On Windows, run the mongod.exe command. Optional: Set the configuration using the --dbpath, --port, --auth, or --replSet options. Use the mongo command to verify that the connection is successful.

See all articles