<?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);