Home Database Mysql Tutorial Introduction to the usage of mongodb and php (code example)

Introduction to the usage of mongodb and php (code example)

Mar 23, 2019 pm 05:08 PM
mongodb php

This article brings you an introduction to the usage of mongodb and php (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Mognodb database connection.

Default format

$m = new Mongo();
//这里采用默认连接本机的27017端口,当然也可以连接远程主机如  192.168.0.4:27017,如果端口是27017,端口可以省略。
Copy after login

Standard connection

$m = new Mongo("mongodb://${username}:${password}@localhost");
Copy after login

Instance:

$m = new Mongo("mongodb://127.0.0.1:27017/admin:admin");
Copy after login

The user name and password of the database are both admin

Database operation

Insert data

<?php
//这里采用默认连接本机的27017端口,当然你也可以连接远程主机如192.168.0.4:27017
//如果端口是27017,端口可以省略
$m = new Mongo("mongodb://127.0.0.1:27017/admin:admin");
//选择comedy数据库,如果以前没该数据库会自动创建,也可以用$m->selectDB("comedy");
$db = $m->comedy;
//选择comedy里面的collection集合,相当于RDBMS里面的表,也可以使用
$collection = $db->collection;
$db->selectCollection("collection");
/*********添加一个元素**************/
$obj = array("title" => "php1", "author" => "Bill Watterson");
//将$obj 添加到$collection 集合中
$collection->insert($obj);
/*********添加另一个元素**************/
$obj = array("title" => "huaibei", "online" => true);
$collection->insert($obj);
//$query = array("title" => "huaibei");
$query = array( "_id" => $obj['_id'] );
$cursor = $collection->find($query);
//遍历所有集合中的文档
foreach ($cursor as $obj) {
   echo $obj["title"] . "\n";
   echo $obj["_id"] . "\n";
}
//断开MongoDB连接
$m->close();
Copy after login

Conditional query

mysql: id = 123
mongo: array(‘id’=>123)
mysql: name link ’%bar%’
mongo: array(‘name’ => new MongoRegex(‘/.*bar.*/i’))
mysql: where id > 10
mongo: array(‘id’ => array(‘$gt’ => 10))
mysql: where id >= 10
mongo: array(‘id’ => array(‘$gte’ => 10))
mysql: where id < 10
mongo: array(‘id’ => array(‘$lt’ => 10))
mysql: where id <= 10
mongo: array(‘id’ => array(‘$lte’ => 10))
mysql: where id > 1 and id < 10
mongo: array(‘id’ => array(‘$gt’ => 1,’$lt’ => 10))
mysql: where id <> 10
mongo: array(‘id’ => array(‘$ne’ => 10))
mysql: where id in(123)
mongo: array(‘id’ => array(‘$in’ => array(1,2,3)))
mysql: where id not in(123)
mongo: array(‘id’ => array(‘$nin’ => array(1,2,3)))
mysql: where id = 2 or id = 9
mongo: array(‘id’ => array(‘$or’ => array(array(‘id’=>2),array(‘id’=>9))))
mysql: order by name asc
mongo: array(‘sort’=>array(‘name’=>1))
mysql: order by name desc
mongo: array(‘sort’=>array(‘name’=>-1))
mysql: limit 0,2
mongo: array(‘limit’=>array(‘offset’=>0,’rows’=>2))
mysql: select name,email
mongo: array(‘name’,'email’)
mysql: select count(name)
mongo: array(‘COUNT’) //注意:COUNT为大写
Copy after login

When querying, each Object will automatically generate a unique_ when it is inserted. id, which is equivalent to the primary key in RDBMS, is very convenient for querying (_id is different for each one, much like an automatically increased id)

<?php
$param = array("name" => "joe");
$collection->insert($param);
$joe = $collection->findOne(array("_id" => $param['_id']));
print_R($joe);
$m->close();
Copy after login

Return result: Array ( [_id] => MongoId Object ( [$id] => 4fd30e21870da83416000002 ) [name] => joe )

Change field value

<?php
$sign = array("title" => 'php1');
$param = array("title" => 'php1','author'=>'test');
$joe = $collection->update($sign, $param);
Copy after login

Delete a database

$m -> dropDB(“comedy”);
Copy after login

List all available databases

$m->listDBs();   //无返回值
Copy after login

Create a MongoDB object

<?php
$mo = new Mongo();
$db = new MongoDB($mo,’dbname’);//通过创建方式获得一个MongoDB对象
Copy after login

Delete the current DB

<?php
$db = $mo->dbname;
$db->drop();
Copy after login

Get the current database name

<?php
$db = $mo->dbname;
$db->_tostring();
Copy after login

Select the desired collection:

//A:
$mo = new Mongo();
$coll = $mo->dbname->collname;//获得一个collection对象
//B:
$db = $mo->selectDB(’dbname’);
$coll = $db->collname;
//C:
$db = $mo->dbname;
$coll = $db->collname;
//D:
$db = $mo->dbname;
$coll = $db->selectCollectoin(’collname’);//获得一个collection对象
Copy after login

Insert data (MongoCollection object

$coll = $mo->db->foo;
$a = array(’a’=>’b’);
$options = array(’safe’=>true);
$rs  =$coll->insert($a,$options);
Copy after login

Delete records in the database (MongoCollection object)

$coll = $mo->db->coll;
$c = array(’a’=>1,’s’=>array(’$lt’=>100));
$options = array(’safe’=>true);
$rs = $coll->remove($c,$options);
Copy after login

Update records in the database (MongoCollection object)

$coll = $mo->db->coll;
$c = array(’a’=>1,’s’=>array(’$lt’=>100));
$newobj = array(’e’=>’f’,’x’=>’y’);
$options = array(’safe’=>true,’multiple’=>true);
$rs = $coll->remove($c,$newobj,$options);
Copy after login

Query the collection to obtain a single record (MongoCollection class)

$coll = $mo->db->coll;
$query = array(’s’=>array(’$lt’=>100));
$fields = array(’a’=>true,’b’=>true);
$rs = $coll->findOne($query,$fields);
Copy after login

Query the collection to obtain multiple records (MongoCollection class)

$coll = $mo->db->coll;
$query = array(’s’=>array(’$lt’=>100));
$fields = array(’a’=>true,’b’=>true);
$cursor = $coll->find($query,$fields);
//排序
$cursor->sort(array(‘字段’=>-1));(-1倒序,1正序)
//跳过部分记录
$cursor->skip(100);跳过100行
//只显示部分记录
$cursor->limit(100);只显示100行
返回一个游标记录对象MongoCursor。
Copy after login

Operations for the cursor object MongoCursor (MongoCursor class)

$cursor = $coll->find($query,$fields);
while($cursor->hasNext()){
$r = $cursor->getNext();
var_dump($r);
}
//或者
$cursor = $coll->find($query,$fields);
foreache($cursor as $k=>$v){
var_dump($v);
}
//或者
$cursor = $coll->find($query,$fields);
$array= iterator_to_array($cursor);
Copy after login

This article ends here It’s all over. For more other exciting content, you can pay attention to the mongodb video tutorial column on the PHP Chinese website!

The above is the detailed content of Introduction to the usage of mongodb and php (code example). 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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)

How can you prevent a class from being extended or a method from being overridden in PHP? (final keyword) How can you prevent a class from being extended or a method from being overridden in PHP? (final keyword) Apr 08, 2025 am 12:03 AM

In PHP, the final keyword is used to prevent classes from being inherited and methods being overwritten. 1) When marking the class as final, the class cannot be inherited. 2) When marking the method as final, the method cannot be rewritten by the subclass. Using final keywords ensures the stability and security of your code.

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: Is It Dying or Simply Adapting? PHP: Is It Dying or Simply Adapting? Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

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

H5: Tools, Frameworks, and Best Practices H5: Tools, Frameworks, and Best Practices Apr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

Composer Expertise: What Makes Someone Skilled Composer Expertise: What Makes Someone Skilled Apr 11, 2025 pm 12:41 PM

To become proficient when using Composer, you need to master the following skills: 1. Proficient in using composer.json and composer.lock files, 2. Understand how Composer works, 3. Master Composer's command line tools, 4. Understand basic and advanced usage, 5. Familiar with common errors and debugging techniques, 6. Optimize usage and follow best practices.

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

See all articles