分享下php操作MongoDB简明教程,包括连接、新增、修改、删除、查询等。
实例:

  1. <?php
  2. //连接localhost:27017
  3. $conn = new Mongo();
  4. //连接远程主机默认端口
  5. $conn = new Mongo('test.com');
  6. //连接远程主机22011端口
  7. $conn = new Mongo('test.com:22011');
  8. //MongoDB有用户名密码
  9. $conn = new Mongo("mongodb://${username}:${password}@localhost")
  10. //MongoDB有用户名密码并指定数据库blog
  11. $conn = new Mongo("mongodb://${username}:${password}@localhost/blog");
  12. //多个服务器
  13. $conn = new Mongo("mongodb://localhost:27017,localhost:27018");
  14. //选择数据库blog
  15. $db = $conn->blog;
  16. //制定结果集(表名:users)
  17. $collection = $db->users;
  18. //新增
    // www.jbxue.com
  19. $user = array('name' => 'caleng', 'email' => 'admin#admin.com');
  20. $collection->insert($user);
  21. //修改
  22. $newdata = array('$set' => array("email" => "[email protected]"));
  23. $collection->update(array("name" => "caleng"), $newdata);
  24. //删除
  25. $collection->remove(array('name'=>'caleng'), array("justOne" => true));
  26. //查找
  27. $cursor = $collection->find();
  28. var_dump($cursor);
  29. //查找一条
  30. $user = $collection->findOne(array('name' => 'caleng'), array('email'));
  31. var_dump($user);
  32. //关闭数据库
  33. $conn->close();
10-28 20:44