php之mongodb插入数据后如何返回当前插入记录ID

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php  
/**
*插入记录
*参数:
*$table_name:表名
*$record:记录
*
*返回值:
*成功:true
*失败:false
*/
function insert($table_name,$record){
$dbname = $this->curr_db_name;
try{
$this->mongo->$dbname->$table_name->insert($record,array('safe'=>true));//执行安全写入的方法
return true;
}catch(MongoCursorException $e){
$this->error = $e->getMessage();
return false;
}
}

?>

如上所示,参数$record实际上是个指针引用,当插入成功后$record数组中就会自动返回_id

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Array(  
[0]=>Array(
[username]=>username570
[password]=>password200
)
[1]=>插入前
)

Array(
[0]=>Array(
[username]=>username570
[password]=>password200
[_id]=>MongoId Object(
[$id]=>35jdfas8dfsafaa9869
)
)
[1]=>999
)

另外注意返回的$record["_id"]是个MongoId对象,可以直接作为mongodb查询条件来使用,不要再来回转换了。