zoukankan      html  css  js  c++  java
  • PHP Mongodb 基本操作

    <?php

    include "config/config.inc.php";
    $host = $config['host'];
    $port = $config['port'];


    $m = new MongoClient("mongodb://{$host}:{$port}");
    $db = $m->demo;
    $table = $db->users;

    //insert 插入

    $arr = array('user_name' => 'test2', 'salary' => 100000);
    $table->insert($arr);

    //findOne 获取一条数据
    $data = $table->findOne();

    //查询条件

    $where = array('_id' => new MongoId('51fcca7bb1b6650817007f5c'));

    //set 修改节点

    $table->update($where , array('$set' => array('performance' => array( array('class1' => 10, 'class2' => 99, 'class3' => 98) ))));

    for($i=1; $i<=100; $i++){
      $arr = array('class1' => 100, 'class2' => 100, 'class3' => 100);

      //push 往节点添加数据,不判断值是否存在
      $table->update($where , array('$push' => array('performance' => $arr)));

      //addToSet 往节点添加数据,存在相同的值则不添加
      $table->update($where , array('$addToSet' => array('performance' => array('$each' => array($arr)))));
    }

    //find 获取所有数据

    $result = $table->find($where);

    //获取游标数据,并转换为数组

    $data = iterator_to_array($result);
    foreach($data as $row){
      echo (string)$row['_id'] . ' ' . $row['user_name'];

      if(!empty($row['performance'])){
        $performance = $row['performance'];

        foreach($performance as $key => $val){
        echo ' ' . $key . ' = ' . $val . ' ';
      }
    }
    echo '</br>';
    }

    //游标取值

    while($result->hasNext()){
      $row = $result->getNext();
      echo (string)$row['_id'] . ' ' . $row['user_name'];

      if(!empty($row['performance'])){
        $performance = $row['performance'];

        foreach($performance as $key => $val){
          echo ' ' . $key . ' = ' . $val . ' ';
        }
      }
      echo '</br>';
     }

    // slice 对子文档分页
    $result = $table->findOne($where, array('performance' => array( '$slice' => array(2, 3) ) ));

    var_dump($result);

  • 相关阅读:
    oracle12 安装
    ORACLE重装之后恢复数据库,相当于sqlserver的附加数据库
    git
    P1323 删数游戏(技巧)
    P2486 【SDOI2011】 染色
    P1084 【NOIP 2012】 疫情控制
    前缀、中缀、后缀表达式
    【P1979】 NOIP2013 华容道
    P2601 【ZJOI2009】对称的正方形
    NOIP2015 运输计划
  • 原文地址:https://www.cnblogs.com/sidesky/p/3235095.html
Copyright © 2011-2022 走看看