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 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)

How to configure MongoDB automatic expansion on Debian How to configure MongoDB automatic expansion on Debian Apr 02, 2025 am 07:36 AM

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

Soland's feeding-level hair-raising airdrop tutorial: 0 cost, no routines, no counter-playing! Soland's feeding-level hair-raising airdrop tutorial: 0 cost, no routines, no counter-playing! Jun 25, 2024 pm 07:13 PM

Soland's feeding-level lubbing tutorial: 0 cost, no routines, no feedback! Recently, hair removal has once again become a topic of discussion among many friends in the currency circle. Of course, this time everyone is generally disappointed or even angry. The reason is for no other reason. First, there was the tug-of-war of Layerzero’s witch screening batch screening, and then the PUA king ZKsync’s Airdrops have caused many people to complain that they were severely criticized, and some even spent tens of thousands of dollars in gas and interaction costs, and the final benefit was less than one-tenth, not counting the time spent and other costs. The two "King of Heaven" level projects have made many people want to quit the terry circle. In fact, we think it is not necessary here, because there are still many opportunities in the encrypted track. Regardless of the scale, project parties have a need to promote it.

How to ensure high availability of MongoDB on Debian How to ensure high availability of MongoDB on Debian Apr 02, 2025 am 07:21 AM

This article describes how to build a highly available MongoDB database on a Debian system. We will explore multiple ways to ensure data security and services continue to operate. Key strategy: ReplicaSet: ReplicaSet: Use replicasets to achieve data redundancy and automatic failover. When a master node fails, the replica set will automatically elect a new master node to ensure the continuous availability of the service. Data backup and recovery: Regularly use the mongodump command to backup the database and formulate effective recovery strategies to deal with the risk of data loss. Monitoring and Alarms: Deploy monitoring tools (such as Prometheus, Grafana) to monitor the running status of MongoDB in real time, and

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:

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

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.

Major update of Pi Coin: Pi Bank is coming! Major update of Pi Coin: Pi Bank is coming! Mar 03, 2025 pm 06:18 PM

PiNetwork is about to launch PiBank, a revolutionary mobile banking platform! PiNetwork today released a major update on Elmahrosa (Face) PIMISRBank, referred to as PiBank, which perfectly integrates traditional banking services with PiNetwork cryptocurrency functions to realize the atomic exchange of fiat currencies and cryptocurrencies (supports the swap between fiat currencies such as the US dollar, euro, and Indonesian rupiah with cryptocurrencies such as PiCoin, USDT, and USDC). What is the charm of PiBank? Let's find out! PiBank's main functions: One-stop management of bank accounts and cryptocurrency assets. Support real-time transactions and adopt biospecies

MongoDB and relational database: a comprehensive comparison MongoDB and relational database: a comprehensive comparison Apr 08, 2025 pm 06:30 PM

MongoDB and relational database: In-depth comparison This article will explore in-depth the differences between NoSQL database MongoDB and traditional relational databases (such as MySQL and SQLServer). Relational databases use table structures of rows and columns to organize data, while MongoDB uses flexible document-oriented models to better suit the needs of modern applications. Mainly differentiates data structures: Relational databases use predefined schema tables to store data, and relationships between tables are established through primary keys and foreign keys; MongoDB uses JSON-like BSON documents to store them in a collection, and each document structure can be independently changed to achieve pattern-free design. Architectural design: Relational databases need to pre-defined fixed schema; MongoDB supports

See all articles