Summary of MongoDB tips and precautions
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" : [] }
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" ] } )
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}}
update json:
{$unset:{"name":""}}
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
-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
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"]})
can also be added in the admin database:
db.createUser({"user":"test","pwd":"123456","roles":[{"role":"readWrite","db":"test"},"readWrite"]})
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
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
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:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



.NET 4.0 is used to create a variety of applications and it provides application developers with rich features including: object-oriented programming, flexibility, powerful architecture, cloud computing integration, performance optimization, extensive libraries, security, Scalability, data access, and mobile development support.

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

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

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.

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

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

Currency Contract: A double-edged sword with high risk and high returns. How to increase the probability of profit? Many veterans in the currency circle have been attracted by the huge potential of contract trading, which can not only bring generous returns but also lead to huge losses. Contract trading is essentially a derivative of digital currency, and its high risk and high returns have attracted much attention. So, how to increase the probability of profit in currency circle contract trading? This requires some key skills. This article will explore in-depth how to reduce risks and improve profitability. Contract profit strategy in the currency circle: In the volatile cryptocurrency market, if you want to achieve stable profits in contract trading, you need to formulate a comprehensive strategy and strictly implement it: Risk management first: setting a stop loss point is the key. Set the stop loss price in advance to control potential losses and avoid single transactions

Sorting index is a type of MongoDB index that allows sorting documents in a collection by specific fields. Creating a sort index allows you to quickly sort query results without additional sorting operations. Advantages include quick sorting, override queries, and on-demand sorting. The syntax is db.collection.createIndex({ field: <sort order> }), where <sort order> is 1 (ascending order) or -1 (descending order). You can also create multi-field sorting indexes that sort multiple fields.
