Heim  >  Artikel  >  Backend-Entwicklung  >  So implementieren Sie das Hinzufügen, Löschen, Ändern und Abfragen in PHP Mongodb

So implementieren Sie das Hinzufügen, Löschen, Ändern und Abfragen in PHP Mongodb

coldplay.xixi
coldplay.xixiOriginal
2021-03-08 11:33:331768Durchsuche

So implementieren Sie das Hinzufügen, Löschen, Ändern und Abfragen in PHP Mongodb: 1. Dateneinfügung, der Code ist [$res = $collection->insert($doc)] 2. Datenabfrage, der Code ist [$ one = $collection-> findOne(['Vorname)].

So implementieren Sie das Hinzufügen, Löschen, Ändern und Abfragen in PHP Mongodb

Die Betriebsumgebung dieses Tutorials: Windows 7-System, PHP Version 5.6, DELL G3-Computer.

php-Mongodb-Methode zum Implementieren von Hinzufügung, Löschung, Änderung und Abfrage:

Der PHP-Treiber von MongoDB bietet einige Kernklassen für den Betrieb von MongoDB. Im Allgemeinen kann er alle Funktionen in der MongoDB-Befehlszeile und das Format von Parametern implementieren ist grundsätzliche Ähnlichkeit. Versionen vor PHP7 und Versionen nach PHP7 haben unterschiedliche Operationen auf MongoDB. In diesem Artikel wird hauptsächlich die vorherige Version von PHP7 als Beispiel verwendet, um die verschiedenen Operationen von PHP auf MongoDB zu erklären.

1. Dateneinfügung

//insert()
//参数1:一个数组或对象
//参数2:扩展选项
//  fsync:默认为false,若为true则mongo在确认数据插入成功之前将会强制把数据写入硬盘
//  j:默认为false,若为true则mongo在确认数据插入成功之前将会强制把数据写入日志
//  w:默认为1,写操作会被(主)服务器确认,若为0则将不会得到确认,使用复制集时设置为n用于确保主服务器将数据修改成功复制到n个节点后再确认
//  wtimeout:默认为10000(毫秒),用于指定服务器等待接收确认的时间
//  timeout:指定客户端需要等待服务器响应的超时时间(毫秒)
$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo->mf;//选择数据库
$collection = $db->friend;//选择文档集合
$doc = [//定义一个文档,即一个数组
    'First Name' => 'Jet',
    'Last Name' => 'Wu',
    'Age' => 26,
    'Phone' => '110',
    'Address' => [
        'Country' => 'China',
        'City' => 'Shen Zhen'
    ],
    'E-Mail' => [
        '123456@qq.com',
        '666666@sina.com',
        '8888888@qq.com',
        '77887788@qq.com'
    ]
];
$res = $collection->insert($doc);//向集合中插入一个文档
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r($res);//$res[&#39;ok&#39;]=1表示插入成功

2. Datenabfrage

1. Fragen Sie mehrere Dokumente ab:

//findOne()
//参数1:搜索条件
//参数2:指定返回字段,array(&#39;fieldname&#39; => true, &#39;fieldname2&#39; => true)。_id字段总会返回,除非在第二个参数显式加入&#39;_id&#39;=>false。不设置则返回所有字段
$mongo = new MongoClient(&#39;mongodb://localhost:27017&#39;);
$db = $mongo->mf;
$collection = $db->friend;
$one = $collection->findOne([&#39;First Name&#39; => &#39;Jet&#39;]);
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r($one);//返回一个数组,查不到数据则返回NULL

Verwenden Sie verschiedene bedingte Operatoren, um Abfragen zu definieren ee

Benutzen Weitere von der MongoCursor-Klasse bereitgestellte Funktionen:

//find()
//参数1:搜索条件
//参数2:指定返回字段,array(&#39;fieldname&#39; => true, &#39;fieldname2&#39; => true)。_id字段总会返回,除非显式设置为false不返回。不设置则返回所有字段
$mongo = new MongoClient(&#39;mongodb://localhost:27017&#39;);
$db = $mongo->mf;
$collection = $db->friend;
$cursor = $collection->find([&#39;Address.Country&#39; => &#39;China&#39;]);//使用点操作符查找数组元素
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
while($doc = $cursor->getNext()) {//循环读取每个匹配的文档
    print_r($doc);
}

Aggregationsabfrage: Gruppieren Sie Daten für Statistiken

//mongodb分别使用$lt、$lte、$eq、$gte、$gt、$ne表示<、<=、=、>=、>、<>,用于整数字段查询
$mongo = new MongoClient(&#39;mongodb://localhost:27017&#39;);
$db = $mongo->mf;
$collection = $db->friend;
$cursor = $collection->find([&#39;Age&#39; => [&#39;$gt&#39; => 30]]);
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
while($doc = $cursor->getNext()) {
    print_r($doc);
}
  //查询某个字段的所有不重复的值
  $res = $collection->distinct(&#39;Age&#39;);

3. Datenänderung

//$in:匹配多个值中任意一个
$cursor = $collection->find([&#39;Address.Country&#39; => [&#39;$in&#39; => [&#39;China&#39;, &#39;USA&#39;]]]);
 
//$all:匹配多个值中所有值(用于数组字段查询)
$cursor = $collection->find([&#39;E-Mail&#39; => [&#39;$all&#39; => [&#39;123456@qq.com&#39;, &#39;77887788@qq.com&#39;]]]);
 
//$or:或查询
$cursor = $collection->find([&#39;$or&#39; => [[&#39;First Name&#39; => &#39;Jet&#39;], [&#39;Address.Country&#39; => &#39;USA&#39;]]]);
 
//$slice:获取数组字段中指定数目的元素,位于find()函数第二个参数中
$cursor = $collection->find([&#39;First Name&#39; => &#39;Jet&#39;], [&#39;E-Mail&#39; => [&#39;$slice&#39; => 2]]);//只返回前两个email
$cursor = $collection->find([&#39;First Name&#39; => &#39;Jet&#39;], [&#39;E-Mail&#39; => [&#39;$slice&#39; => -2]]);//只返回最后两个email
$cursor = $collection->find([&#39;First Name&#39; => &#39;Jet&#39;], [&#39;E-Mail&#39; => [&#39;$slice&#39; => [1, 2]]]);//忽略第一个,返回接下来两个
 
//$exists:根据某个字段是否有设置值进行查询
$cursor = $collection->find([&#39;Hobby&#39; => [&#39;$exists&#39; => false]]);//查找Hobby字段未设置值的文档
 
//正则表达式查询
$cursor = $collection->find([&#39;First Name&#39; => new MongoRegex(&#39;/^Je/i&#39;)]);//查找First Name字段以Je开头的文档,忽略大小写差异
//排序:1升序,-1降序
$cursor->sort([&#39;Age&#39; => 1]);
 
//忽略前n个匹配的文档
$cursor->skip(1);
 
//只返回前n个匹配的文档(limit()与skip()结合使用可实现数据分页功能)
$cursor->limit(1);
 
//匹配文档的总数
$cursor->count();
 
//指定查询索引
$cursor->hint([&#39;Last Name&#39; => -1]);//若索引不存在则会报错
//聚合查询:对数据进行分组统计
$mongo = new MongoClient(&#39;mongodb://localhost:27017&#39;);
$db = $mongo->mf;
$collection = $db->friend;
$res = $collection->aggregate([
    &#39;$group&#39; => [
        &#39;_id&#39; => &#39;$Address.Country&#39;,//分组字段,注意要加上“$”,这里是根据数组字段某个元素值进行分组
        &#39;total&#39; => [&#39;$sum&#39; => 1],//求总和,表示每匹配一个文档总和就加1
        &#39;maxAge&#39; => [&#39;$max&#39; => &#39;$Age&#39;],//分组中Age字段最大值
        &#39;minAge&#39; => [&#39;$min&#39; => &#39;$Age&#39;]//分组中Age字段最小值
    ]
]);
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r($res);//返回一个数组,$ret[&#39;result&#39;]为数组,存放统计结果
 
 
//存在其它操作的聚合查询:多个操作之间执行先后顺序取决于它们位置的先后顺序
//聚合查询中的所有操作,包括&#39;$group&#39;在内,都是可选的。
$mongo = new MongoClient(&#39;mongodb://localhost:27017&#39;);
$db = $mongo->mf;
$collection = $db->friend;
$res = $collection->aggregate([
    [//过滤条件:只对符合条件的原始文档进行聚合运算,若是放在&#39;$group&#39;之后则是只返回符合条件的结果文档
        &#39;$match&#39; => [&#39;Age&#39; => [&#39;$gt&#39; => 30]]
    ],
    [//指定分组字段、统计字段
        &#39;$group&#39; => [
            &#39;_id&#39; => &#39;$Address.Country&#39;,
            &#39;totalAge&#39; => [&#39;$sum&#39; => &#39;$Age&#39;]//计算各个分组Age字段总和
        ]
    ],
    //以下操作若是放在&#39;$group&#39;之前则在聚合前作用于原始文档,若放在&#39;$group&#39;之后则在聚合后作用于结果文档
    [&#39;$unwind&#39; => &#39;$E-Mail&#39;],//将包含有某个数组类型字段的文档拆分成多个文档,每个文档的同名字段的值为数组中的一个值。
    [&#39;$project&#39; => [&#39;myAge&#39; => &#39;$Age&#39;, &#39;First Name&#39; => &#39;$First Name&#39;]],//指定返回字段,可以对字段进行重命名,格式:返回字段名 => $原来字段名
    [&#39;$skip&#39; => 2],//跳过指定数量的文档
    [&#39;$limit&#39; => 2],//只返回指定数量的文档
    [&#39;$sort&#39; => [&#39;totalAge&#39; => 1]]//排序
]);
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r($res);
4. Datenlöschung.

//update()
//参数1:更新条件,指定更新的目标对象。
//参数2:指定用于更新匹配记录的对象。
//参数3:扩展选项组。
//  upsert:若设置为true,当没有匹配文档的时候会创建一个新的文档。
//  multiple:默认为false,若设置为true,匹配文档将全部被更新。
//  fsync:若设置为true,w参数将被覆盖为0,数据将在更新结果返回前同步到磁盘。
//  w:默认为1;若设置为0,更新操作将不会得到确认;使用复制集时可设置为n,确保主服务器在将修改复制到n个节点后才确认该更新操作
//  j:默认为false,若设置为true,数据将在更新结果返回之前写入到日志中。
//  wtimeout:默认为10000(毫秒),用于指定服务器等待接收确认的时间
//  timeout:指定客户端需要等待服务器响应的超时时间(毫秒)
//注意:若不使用任何修改操作符,则匹配文档将直接被整个替换为参数2指定的对象。
 
//$inc:增加特定键的值,若字段不存在则新建字段并赋值
$mongo = new MongoClient(&#39;mongodb://localhost:27017&#39;);
$db = $mongo->mf;
$collection = $db->friend;
$res = $collection->update([&#39;First Name&#39; => &#39;Jet&#39;], [&#39;$inc&#39; => [&#39;Age&#39; => 2]]);
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r($res);//$res[&#39;ok&#39;]=1表示修改成功,$res[&#39;nModified&#39;]表示修改的文档数量
 
//$set:重置特定键的值,若字段不存在则新建字段并赋值
$res = $collection->update([&#39;First Name&#39; => &#39;Jet&#39;], [&#39;$set&#39; => [&#39;Hobby&#39; => &#39;pingpong&#39;]]);
 
//$unset:删除字段
$res = $collection->update([&#39;First Name&#39; => &#39;Jet&#39;], [&#39;$unset&#39; => [&#39;Hobby&#39; => 1]]);
 
//$rename:重命名字段,若字段不存在则不进行任何操作
$res = $collection->update([&#39;First Name&#39; => &#39;Jet&#39;], [&#39;$rename&#39; => [&#39;Hobby&#39; => &#39;hobby&#39;, &#39;Age&#39; => &#39;age&#39;]]);
//注意:如果文档中已经使用了指定名称的字段,则该字段将会被删除,然后再进行重命名操作。
 
//$setOnInsert:设置了upsert为true,并且发生了插入操作的时候,将某个字段设置为特定的
$res = $collection->update([&#39;First Name&#39; => &#39;jet&#39;], [&#39;$setOnInsert&#39; => [&#39;lang&#39; => &#39;English&#39;]], [&#39;upsert&#39; => true]);
 
//$push:向指定字段添加一个值(作用于数组字段),若字段不存在会先创建字段,若字段值不是数组会报错
$res = $collection->update([&#39;First Name&#39; => &#39;Jet&#39;], [&#39;$push&#39; => [&#39;E-Mail&#39; => &#39;123123@qq.com&#39;]]);
 
//$push:向指定字段添加多个值(作用于数组字段),若字段不存在会先创建字段,若字段值不是数组会报错
$res = $collection->update([&#39;First Name&#39; => &#39;Jet&#39;], [&#39;$pushAll&#39; => [&#39;E-Mail&#39; => [&#39;666@qq.com&#39;, &#39;8888888@qq.com&#39;]]]);
 
//使用$push和$each向某个字段添加多个值(作用于数组字段),若字段不存在会先创建字段,若字段值不是数组会报错
$res = $collection->update([&#39;First Name&#39; => &#39;Jet&#39;], [&#39;$push&#39; => [&#39;E-Mail&#39; => [&#39;$each&#39; => [&#39;123123@qq.com&#39;, &#39;666@qq.com&#39;]]]]);
 
//$addToSet:将数据添加到数组中(只在目标数组没有该数据的时候才将数据添加到数组中)
$res = $collection->update([&#39;First Name&#39; => &#39;Jet&#39;], [&#39;$addToSet&#39; => [&#39;E-Mail&#39; => &#39;123123@qq.com&#39;]]);
$res = $collection->update([&#39;First Name&#39; => &#39;Jet&#39;], [&#39;$addToSet&#39; => [&#39;E-Mail&#39; => [&#39;$each&#39; => [&#39;123123@qq.com&#39;, &#39;666@qq.com&#39;]]]]);
 
//$pop:从数组中删除一个元素,-1表示删除第一个元素,1表示删除最后一个元素(其实负数都删除第一个元素,0或正数都删除最后一个元素)
$res = $collection->update([&#39;First Name&#39; => &#39;Jet&#39;], [&#39;$pop&#39; => [&#39;E-Mail&#39; => 1]]);
 
//$pull:删除数组中所有指定值
$res = $collection->update([&#39;First Name&#39; => &#39;Jet&#39;], [&#39;$pull&#39; => [&#39;E-Mail&#39; => &#39;123123@qq.com&#39;]]);
 
//$pullAll:删除数组中多个元素的所有值
$res = $collection->update([&#39;First Name&#39; => &#39;Jet&#39;], [&#39;$pullAll&#39; => [&#39;E-Mail&#39; => [&#39;123123@qq.com&#39;, &#39;666@qq.com&#39;]]]);

Re Aktuelle Videoempfehlungen:

PHP Video Tutorial

Das obige ist der detaillierte Inhalt vonSo implementieren Sie das Hinzufügen, Löschen, Ändern und Abfragen in PHP Mongodb. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn