zoukankan      html  css  js  c++  java
  • php--MongoDB的使用

    添加

    $collection = (new MongoDBClient)->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 MongoDBClient)->test->zips;
    // 查找单条
    // 根据id查
    $document = $collection->findOne(['_id' => '94301']);
    // 根据系统自动生成的id查
    $data = $collection->findOne(['_id' => new MongoDBBSONObjectId('5c841cc9b0b4f48a3a05b1e2')]);
    
    // 查找多条
    $cursor = $collection->find(['city' => 'JERSEY CITY', 'state' => 'NJ']);
    // 多条件查询
    $cursor = $collection->find(
    // 查询条件
        [
            'cuisine' => 'Italian',
            'borough' => 'Manhattan',
            // 使用正则查询
            'city' => new MongoDBBSONRegex('^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']);
    
  • 相关阅读:
    利用Python编写简单的Web静态服务器(TCP协议)
    UDP-TCP介绍与区别
    Linux基本知识-命令
    Python中多线程与join()的应用
    Python实例---对一组含有四则运算,括号,空格的字符串进行计算
    分组查询注意事项
    oracle分页查询
    springMVC文件上传配置
    ssm网站页面乱码问题解决
    redis-server.exe闪退
  • 原文地址:https://www.cnblogs.com/peilanluo/p/10503161.html
Copyright © 2011-2022 走看看