连接
new MongoClient($dsn,$options);
$this->getMongoClient()->selectCollection($this->mongo_db,$collection_name);
添加
->getMongoCollection()->insert($data);
获取总数
->getMongoCollection()->count($where);
获取列表(分页)
$data = $this->_activity->getMongoCollection()->find($where)->sort($sort)->skip(($page - 1) * $limit)->limit($limit);
$list = iterator_to_array($data);
删除
getMongoCollection()->remove($where);
用 in 查询
$cursor = $collection->find(array('status' => 0, 'sid' => array('$in' => $setting2)));
大于 小于 大于等于 小于等于
$gt:大于
$lt:小于
$gte:大于或等于
$lte:小于或等于
$unset: 删除字段
$ne 不等于
更新
只更新某些字段
//只更新mobile
$_user -> getMongoCollection() -> update($user_where,array('$set'=>array('mobile'=>$mobile)));
存在则更新,不存在则添加
$c->update(
array("uri" => "/summer_pics"),
array('$inc' => array("page hits" => 1)),
array("upsert" => true)
);
返回
array(6) {
["ok"]=>
float(1)
["nModified"]=>
int(1)
["n"]=>
int(1)
["err"]=>
NULL
["errmsg"]=>
NULL
["updatedExisting"]=>
bool(true)
}
更新多条记录
$c->update(
array("is_hide" => 0),
array('$set' => array("is_deleted" => 1)),
array("multiple" => true)
);
更新 字段 +1 加1
-> update($where, array('$inc'=>array("share_count" => 1)));
查询 sum
如
select sum(id) from table where uid=5 and gender=1
{
"_id": ObjectId("57c037cdc5efe68c4d8b46bf"),
"activity_id": "57beb468c5efe60f058b4631",
"user_id": "57c02989c5efe68c4d8b4692",
"play_count": NumberLong(0),
"share_count": NumberLong(0),
"date": NumberLong(1472140800)
}
{
"_id": ObjectId("57c0379ac5efe68c4d8b46bd"),
"activity_id": "57beb468c5efe60f058b4631",
"user_id": "57c02989c5efe68c4d8b4692",
"play_count": NumberLong(0),
"share_count": NumberLong(0),
"date": NumberLong(1472140800)
}
$info = $this->_user -> getMongoCollection() -> aggregate(
array(
'$match' => array(
'$and'=> array(
array('activity_id' => $activity_id),
array('user_id' => $user_id)
)
)
),
array(
'$group' => array(
'_id'=> 'null',
'total'=>array(
'$sum'=>'$play_count'
)
)
));
结果
array(2) {
["result"]=>
array(1) {
[0]=>
array(2) {
["_id"]=>
string(4) "null"
["total"]=>
int(31)
}
}
["ok"]=>
float(1)
}
查询 排序
cursor -> sort(array('字段'=>1(ASC)或-1(DESC))) 排序,一定要用在find()之后
随机查询一条记录
$count = 记录总数
cursor -> find($where) -> skip(rand(0,$count)) -> limit(1);
更新/添加ISODate时间
use MongoDB\BSON\UTCDateTime;
$this->date = new UTCDateTime();
$this.save();
结果date
字段会是这样ISODate("2019-03-26T15:22:16.636+08:00")
更新对象里的数组的对象
数据:
{
"_id" : ObjectId("5c991742b520d97e6e4104f2"),
"userId" : 3,
"addressList" : [
{
"_id" : ObjectId("5c99d499071fad9685c1f47c"),
"isDefault" : 0,
"province" : "广东省",
"city" : "广州市"
},
{
"_id" : ObjectId("5c99d4a9071fad9685c1f47d"),
"isDefault" : 0,
"province" : "广东省",
"city" : "广州市"
},
{
"_id" : ObjectId("5c99960eb520d97e6f0bd9e4"),
"isDefault" : 1,
"province" : "广东省",
"city" : "广州市"
}
]
}
用 $set
操作符将userId
是3
且 addressList
的 _id
是5c99d499071fad9685c1f47c
的city
更新成深圳
db->update(
['userId'=>3, 'addressList._id' => new ObjectID('5c99d499071fad9685c1f47c')],
['$set' => ['addressList.$.city' => '深圳'] ],
['multi' => true,'upsert' => false]
);