添加
$collection = (new MongoDB\Client)->test->users;
// 增加一条
$insertOneResult = $collection->insertOne([
'username' => 'admin',
'email' => 'admin@example.com',
'name' => 'Admin User',
]);
// 增加多条
$insertManyResult = $collection->insertMany([
[
'username' => 'admin',
'email' => 'admin@example.com',
'name' => 'Admin User',
],
[
'username' => 'test',
'email' => 'test@example.com',
'name' => 'Test User',
],
]);
查询
$collection = (new MongoDB\Client)->test->zips;
// 查找单条
// 根据id查
$document = $collection->findOne(['_id' => '94301']);
// 根据系统自动生成的id查
$data = $collection->findOne(['_id' => new MongoDB\BSON\ObjectId('5c841cc9b0b4f48a3a05b1e2')]);
// 查找多条
$cursor = $collection->find(['city' => 'JERSEY CITY', 'state' => 'NJ']);
// 多条件查询
$cursor = $collection->find(
// 查询条件
[
'cuisine' => 'Italian',
'borough' => 'Manhattan',
// 使用正则查询
'city' => new MongoDB\BSON\Regex('^garden', 'i'),
'city' => ['$regex' => '^garden', '$options' => 'i'],
],
// 查询字段
[
'projection' => [
'name' => 1,
'borough' => 1,
'cuisine' => 1,
],
// 查询条数
'limit' => 4,
// 排序
'sort' => ['pop' => -1],
// 跳过条数
‘skip’ => 3,
],
);
// 聚合
$cursor = $collection->aggregate([
// 分组,_id为分组的依据,以下为常用表达式
// $sum:计算总和,$sum:1同count表示计数
// $avg:计算平均值
// $min:获取最小值
// $max:获取最大值
// $push:在结果文档中插入值到一个数组中
// $first:根据资源文档的排序获取第一个文档数据
// $last:根据资源文档的排序获取最后一个文档数据
['$group' => ['_id' => '$state', 'count' => ['$sum' => 1]]],
['$sort' => ['count' => -1]],
['$limit' => 5],
// 过滤数据
[$match => [age => [$gt => 20]]],
]);
修改
$updateResult = $collection->updateOne(
['state' => 'ny'],
['$set' => ['country' => 'us']]
);
$updateResult = $collection->updateMany(
['state' => 'ny'],
['$set' => ['country' => 'us']]
);
删除
$deleteResult = $collection->deleteOne(['state' => 'ny']);
$deleteResult = $collection->deleteMany(['state' => 'ny']);