Creation and deletion of MongoDB documents (php code example)
Note that all code examples in this article are demonstrated using PHP code.
##Install the MongoDB extension
# #Extension package installation address: https://pecl.php.net/package/mongodb
Download the most stable version, and then upload the expansion package to the server.
# 解压 tar zxf mongodb-1.8.0.tgz cd mongodb-1.8.0 # 安装 /usr/local/php/bin/phpize ./configure --with-php-config=/usr/local/php/bin/php-config make & make install # 修改php配置文件php.ini # 加入一行extension=mongodb # 测试 php -m | grep mongodb
mongodb extension tutorial: https://docs.mongodb.com/php-library/current/reference/
Using phplibcomposer require mongodb/mongodb
Insert documentSimilar to Mysql, MongoDB can also insert single or multiple documents into documents. Let’s look at inserting a single entry:
$mongo = new MongoDB\Client(); $collect = $mongo->users->users; $collect->insertOne(['name'=> 'james', 'age' => 35]);
If the _id field is not declared, this operation will automatically create an _id field for the new document. Of course, we can also manually specify the value of _id
$collect->insertOne(['_id' => 1,'name'=> 'james', 'age' => 35]);
This function returns the MongoDB\InsertOneResult object if successfully executed, and an exception will be thrown if it fails.
Let’s see how to insert multiple documents:
$collect->insertMany([ [ 'name'=>'paul', 'age' => 34], [ 'name'=>'durant', 'age' => 31], [ 'name'=> 'curry', 'age' => 31] ]);
It should be noted that during batch insertion, if one of the documents fails to be inserted, the subsequent ones will not continue to be inserted, but The previous one will be inserted.
# 第一条会插入成功,第二条时插入失败,后面的也不会继续插入 $collect->insertMany([ [ 'name'=>'paul', 'age' => 34], ['_id'=> 1, 'name'=> 'jeans', 'age' => 1], // _id=1已存在 [ 'name'=>'durant', 'age' => 31], [ 'name'=> 'curry', 'age' => 31] ]);
If you want to ignore errors and continue inserting, you need to add an option ordered to the method and set it to false.
$collect->insertMany([ [ 'name'=>'jay', 'age' => 34], ['_id'=> 1, 'name'=> 'jeans', 'age' => 1], // _id=1已存在 [ 'name'=>'xtf', 'age' => 31], ],['ordered' => false]);
Note: You can insert if you encounter the above error Success, but the statement throws an exception. If you want to ignore the error and continue the execution of the program, you need to catch the exception.
Delete document
Note: Deletion is a dangerous operation and cannot be restored or undone.Delete documents through query statements:
/** * 目前有4个name为james的文档 */ # 删除一个文档 $ret = $collect->deleteOne(['name'=>'james']); printf($ret->getDeletedCount()); // 1 # 删除满足条件的所有文档 $ret = $collect->deleteMany(['name'=>'james']); printf($ret->getDeletedCount());
Delete all documents (in fact, the entire collection is deleted):
$collect->drop();
Creation and deletion of MongoDB documents, It's very simple to use.
Recommended: "
The above is the detailed content of Creation and deletion of MongoDB documents (php code example). 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



It is recommended to use the latest version of MongoDB (currently 5.0) as it provides the latest features and improvements. When selecting a version, you need to consider functional requirements, compatibility, stability, and community support. For example, the latest version has features such as transactions and aggregation pipeline optimization. Make sure the version is compatible with the application. For production environments, choose the long-term support version. The latest version has more active community support.

Node.js is a server-side JavaScript runtime, while Vue.js is a client-side JavaScript framework for creating interactive user interfaces. Node.js is used for server-side development, such as back-end service API development and data processing, while Vue.js is used for client-side development, such as single-page applications and responsive user interfaces.

The data of the MongoDB database is stored in the specified data directory, which can be located in the local file system, network file system or cloud storage. The specific location is as follows: Local file system: The default path is Linux/macOS:/data/db, Windows: C:\data\db. Network file system: The path depends on the file system. Cloud Storage: The path is determined by the cloud storage provider.

The MongoDB database is known for its flexibility, scalability, and high performance. Its advantages include: a document data model that allows data to be stored in a flexible and unstructured way. Horizontal scalability to multiple servers via sharding. Query flexibility, supporting complex queries and aggregation operations. Data replication and fault tolerance ensure data redundancy and high availability. JSON support for easy integration with front-end applications. High performance for fast response even when processing large amounts of data. Open source, customizable and free to use.

MongoDB is a document-oriented, distributed database system used to store and manage large amounts of structured and unstructured data. Its core concepts include document storage and distribution, and its main features include dynamic schema, indexing, aggregation, map-reduce and replication. It is widely used in content management systems, e-commerce platforms, social media websites, IoT applications, and mobile application development.

On Linux/macOS: Create the data directory and start the "mongod" service. On Windows: Create the data directory and start the MongoDB service from Service Manager. In Docker: Run the "docker run" command. On other platforms: Please consult the MongoDB documentation. Verification method: Run the "mongo" command to connect and view the server version.

The MongoDB database file is located in the MongoDB data directory, which is /data/db by default, which contains .bson (document data), ns (collection information), journal (write operation records), wiredTiger (data when using the WiredTiger storage engine ) and config (database configuration information) and other files.

Solutions to resolve Navicat expiration issues include: renew the license; uninstall and reinstall; disable automatic updates; use Navicat Premium Essentials free version; contact Navicat customer support.
