⑴ 求助安装 php mongo 扩展
Windows安装PHP MongoDB扩展
本文将讲述一下在Wamp环境下安装MongoDB扩展的过程,大家可以略作参考
Linux 版本的可以参考之前发布的Linux安装PHP MongoDB扩展
安装环境
系统环境:Windows 7 64位
Apache版本:2.4.9
PHP版本:5.5.12
MongoDB版本:3.2.6
Wamp版本:wamp 2.5 64位
在windows下安装mongodb的扩展比Linux环境稍微复杂点
安装步骤
一、确定php的compiler
通过查看phpinfo()可以确定
可以看到,Compiler是VC11
二、确定php是否是线程安全版本
通过查看phpinfo()可以确定
如果是enabled,则说明是Thread safety版本
三、下载对应的php-mongodb版本
根据前面所得到的信息,需要下载同时符合php5.5,VC11,ts(thread safety),64位的扩展
一般来说,官网的资料是最新和最全的,推荐到官网去下载。下载地址是:http://windows.php.net/downloads/pecl/releases/mongo/。我选择的是1.6.10版本的
下载php_mongo-1.6.10-5.5-ts-vc11-x64.zip回来,把里面的php-mongo.dll复制到php的插件目录下,我本机是:D:\wamp\bin\php\php5.5.12\ext
四、在系统环境变量中加入libsasl.dll的所在路径
根据http://php.net/manual/en/mongo.installation.php的介绍,安装mongo扩展需要依赖libsasl.dll, 所以要在系统环境变量中加入该目录。该目录一般是php的根目录。在wamp 2.5下,如果wamp的安装盘是D盘,该目录的位置大概是D:\wamp\bin\php\php5.5.12
五、在php.ini中加入extension=php_mongo.dll
extension=php_mongo.dll这行字需要根据实际情况,有些是extension=php_mongodb.dll,取决于D:\wamp\bin\php\php5.5.12\ext目录中mongo扩展的名字。
注意:wamp中一般有两个php.ini文件,一个是位于php的根目录下,一个是apache的根目录下,需要添加的是apache根目录下的php.ini。
六、重启wamp服务
最好是完全退出后再打开
最后,上图体验一下安装后的美妙时刻。
安装成功后,查看phpinfo版面,会有以下内容显示。
至此, Windows 下添加php mongo扩展成功结束。
⑵ 为什么我用php查询mongodb数据库中的某个集合中的文档的条数,得到的结果和实际情况不一致
我也遇到过:
官方文档解释了这种现象的原因以及解决方法:
不准确的原因:
操作的是分片的集合(前提);
shard分片正在做块迁移,导致有重复数据出现
存在孤立文档(因为不正常关机、块迁移失败等原因导致)
解决方法
使用聚合aggregate的方式查询count数量,shell命令如下:
db.collection.aggregate(
[
{ $group: { _id: null, count: { $sum: 1 } } }
])
也可以直接将原数据导出,将表删除后重新导入就可以了(我是这么处理的)
⑶ 求教mongo字段是索引数组怎么查询啊
mongodb中使用aggregate可以返回数组字段数组的指定索引的元素
参考语句:
{$match:{'id':15}},
{$project:{id:1,"default":1}},
{$unwind:"$default.styles"},
{$match:{'default.styles.status':1}},
{$group:{_id:"$_id","defaults":{$push:"$default.styles"}}}
解释:
1:过滤数据{$match:{'id':15}}
2:获取想要的列{$project:{id:1,"default":1}}
3:获取展开后数组字段{$unwind:"$default.styles"}
4:条件查询数组元素{$match:{'default.styles.status':1}}
5:分组后保存结果{$group:{_id:"$_id","defaults":{$push:"$default.styles"}}}
⑷ php删除数组指定元素并重建索引
mongodb中使用aggregate可以返回数组字段数组的指定索引的元素
参考语句:
{$match:{'id':15}},
{$project:{id:1,"default":1}},
{$unwind:"$default.styles"},
{$match:{'default.styles.status':1}},
{$group:{_id:"$_id","defaults":{$push:"$default.styles"}}}
解释:
1:过滤数据{$match:{'id':15}}
2:获取想要的列{$project:{id:1,"default":1}}
3:获取展开后数组字段{$unwind:"$default.styles"}
4:条件查询数组元素{$match:{'default.styles.status':1}}
5:分组后保存结果{$group:{_id:"$_id","defaults":{$push:"$default.styles"}}}
⑸ aggregate mongodb sort会不会加快速度
当然会加快速度,不过sort的字段最好是已经建立好相关索引的,不然不但不会加快反而变慢。
⑹ mongo聚合查询aggregate查找重复数据,第二次match不生效
mongodb中使用aggregate可以返回数组字段数组的指定索引的元素
参考语句:
{$match:{'id':15}},
{$project:{id:1,"default":1}},
{$unwind:"$default.styles"},
{$match:{'default.styles.status':1}},
{$group:{_id:"$_id","defaults":{$push:"$default.styles"}}}
解释:
1:过滤数据{$match:{'id':15}}
2:获取想要的列{$project:{id:1,"default":1}}
3:获取展开后数组字段{$unwind:"$default.styles"}
4:条件查询数组元素{$match:{'default.styles.status':1}}
5:分组后保存结果{$group:{_id:"$_id","defaults":{$push:"$default.styles"}}}
数据结构如下:
{
"_id" : ObjectId("55dad346ea23e7c11beefce5"),
"id" : 11.0,
"default" : {
"style" : "普通会诊",
"alias" : "",
"money" : "0",
"styles" : [{
"code" : 1,
"style" : "普通会诊",
"alias" : "一般会诊",
"money" : 100,
"status" : 1,
"remark" : "需要患者亲自来到医院"
} {
"code" : 6,
"style" : "夜间门诊",
"alias" : "夜间门诊",
"money" : 100,
"status" : 0,
"remark" : "夜间门诊"
}, {
"code" : 7,
"style" : "其他门诊",
"alias" : "其他门诊",
"money" : 10,
"status" : 0,
"remark" : "其他门诊"
}]
}
}
⑺ MongoDB Aggregate $project中,如果想新加一列常数,如何写
1. Test Data
Data in JSON format, shows the hosting provider for website.
website.json
{ "_id" : 1, "domainName" : "test1.com", "hosting" : "hostgator.com" }
{ "_id" : 2, "domainName" : "test2.com", "hosting" : "aws.amazon.com"}
{ "_id" : 3, "domainName" : "test3.com", "hosting" : "aws.amazon.com" }
{ "_id" : 4, "domainName" : "test4.com", "hosting" : "hostgator.com" }
{ "_id" : 5, "domainName" : "test5.com", "hosting" : "aws.amazon.com" }
{ "_id" : 6, "domainName" : "test6.com", "hosting" : "cloud.google.com" }
{ "_id" : 7, "domainName" : "test7.com", "hosting" : "aws.amazon.com" }
{ "_id" : 8, "domainName" : "test8.com", "hosting" : "hostgator.com" }
{ "_id" : 9, "domainName" : "test9.com", "hosting" : "cloud.google.com" }
{ "_id" : 10, "domainName" : "test10.com", "hosting" : "godaddy.com" }
Imports into a “website” collection.
> mongoimport -d testdb -c website --file website.json
connected to: 127.0.0.1
Mon Jan 13 14:30:22.662 imported 10 objects
Note
If the collection is existed, add --upsert option to override the data.
> mongoimport -d testdb -c website --file website.json --upsert
2. Grouping Example
Uses db.collection.aggregate and $group to perform the data grouping.
2.1 The following example groups by the “hosting” field, and display the total sum of each hosting.
> db.website.aggregate(
{
$group : {_id : "$hosting", total : { $sum : 1 }}
}
);
Output
{
"result" : [
{
"_id" : "godaddy.com",
"total" : 1
},
{
"_id" : "cloud.google.com",
"total" : 2
},
{
"_id" : "aws.amazon.com",
"total" : 4
},
{
"_id" : "hostgator.com",
"total" : 3
}
],
"ok" : 1
}
The equivalent SQL.
SELECT hosting, SUM(hosting) AS total
FROM website
GROUP BY hosting
2.2 Add sorting with $sort.
> db.website.aggregate(
{
$group : {_id : "$hosting", total : { $sum : 1 }}
},
{
$sort : {total : -1}
}
);
Output – Display “total” in descending order. For ascending order, uses $sort : {total : 1}.
{
"result" : [
{
"_id" : "aws.amazon.com",
"total" : 4
},
{
"_id" : "hostgator.com",
"total" : 3
},
{
"_id" : "cloud.google.com",
"total" : 2
},
{
"_id" : "godaddy.com",
"total" : 1
}
],
"ok" : 1
}
2.3 Add $match condition, groups by “hosting” for “aws.amazon.com” only.
> db.website.aggregate(
{
$match : {hosting : "aws.amazon.com"}
},
{
$group : { _id : "$hosting", total : { $sum : 1 } }
}
);
Output
{
"result" : [
{
"_id" : "aws.amazon.com",
"total" : 4
}
],
"ok" : 1
}
More Examples
Refer to this official MongoDB Aggregation guide for more advance aggregation and group examples.
3. Exports Grouping Result to CSV or JSON
Often times, we need to export the grouping results in csv or JSON format. To solve it, inserts the group results in a new collection, and exports the new collection via mongoexport.
3.1 Set the group results in a variable. In this case, the variable name is “groupdata”.
> var groupdata = db.website.aggregate(
{
$group : {_id : "$hosting", total : { $sum : 1 }}
},
{
$sort : {total : -1}
}
);
3.2Inserts groupdata.toArray() into a new collection.
> db.websitegroup.insert(groupdata.toArray());
> db.websitegroup.find().pretty()
{ "_id" : "aws.amazon.com", "total" : 4 }
{ "_id" : "hostgator.com", "total" : 3 }
{ "_id" : "cloud.google.com", "total" : 2 }
{ "_id" : "godaddy.com", "total" : 1 }
>
3.3 Exports the collection “websitegroup” to a csv file.
c:\> mongoexport -d testdb -c websitegroup -f _id,total -o group.csv --csv
connected to: 127.0.0.1
exported 4 records
group.csv
_id,total
"aws.amazon.com",4.0
"cloud.google.com",2.0
"godaddy.com",1.0
"hostgator.com",3.0
3.4 Exports the collection “websitegroup” to a JSON file.
c:\> mongoexport -d testdb -c websitegroup -o group.json
connected to: 127.0.0.1
exported 4 records
group.json
{ "_id" : "aws.amazon.com", "total" : 4 }
{ "_id" : "cloud.google.com", "total" : 2 }
{ "_id" : "godaddy.com", "total" : 1 }
{ "_id" : "hostgator.com", "total" : 3 }
4. Large Sort Operation
Changed in version 2.6 – Read this Memory Restrictions
In MongoDB, the in-memory sorting have a limit of 100M, to perform a large sort, you need enable allowDiskUse option to write data to a temporary file for sorting.
To avoid the sort exceeded memory limit error, enable the allowDiskUse option.
db.website.aggregate(
[
{$group : {_id : "$hosting", total : { $sum : 1 }}},
{$sort : {total : -1}}
],
{allowDiskUse: true}
);
References
MongoDB Aggregation
MongoDB db.collection.aggregate()
Aggregation Pipeline Limits
MongoDB Hello World Example
Tags : group mongodb sort
Share this article on
TwitterFacebookGoogle+
Reader also read :
MongoDB : Sort exceeded memory limit of 104857600 bytes
Spring Data MongoDB – Aggregation Grouping Example
Spring Data MongoDB – Select fields to return
MongoDB – Allow remote access
⑻ MongoDB中聚合的方法使用aggregate()返回的列表中没有$project里面的属性字段,本人初学,请大家指导一下
去掉project看看原始数据有没有查出字段;如果是用对象接收的,你需要看看你的对象里定义这个字段没有;
⑼ mongo php 操作 怎样更新一条数据
PHP操作MongoDB数据库的简单示例。
Mongodb的常用操作
参看手册,php官方的http://us2.php.net/manual/en/mongo.manual.php
也可以参看mongodb官方的教程。
一,Mognodb数据库连接
1)、默认格式
复制代码代码示例:
$m=newMongo();
//这里采用默认连接本机的27017端口,当然也可以连接远程主机如192.168.0.4:27017,如果端口是27017,端口可以省略。
2)、标准连接
$m=newMongo(“mongodb://${username}:${password}@localhost”);
实例:
复制代码代码示例:
$m=newMongo(“mongodb://127.0.0.1:27017/admin:admin”);
数据库的用户名和密码都是admin
数据库操作:
1)、插入数据:
复制代码代码示例:
<?php
//这里采用默认连接本机的27017端口,当然你也可以连接远程主机如192.168.0.4:27017
//如果端口是27017,端口可以省略
$m=newMongo("mongodb://127.0.0.1:27017/admin:admin");
//选择comedy数据库,如果以前没该数据库会自动创建,也可以用$m->selectDB("comedy");
$db=$m->comedy;
//选择comedy里面的collection集合,相当于RDBMS里面的表,也可以使用
$collection=$db->collection;
$db->selectCollection("collection");
/*********添加一个元素**************/
$obj=array("title"=>"php1","author"=>"BillWatterson");
//将$obj添加到$collection集合中
$collection->insert($obj);
/*********添加另一个元素**************/
$obj=array("title"=>"huaibei","online"=>true);
$collection->insert($obj);
//$query=array("title"=>"huaibei");
$query=array("_id"=>$obj['_id']);
$cursor=$collection->find($query);
//遍历所有集合中的文档
foreach($cursoras$obj){
echo$obj["title"]." ";
echo$obj["_id"]." ";
}
//断开MongoDB连接
$m->close();
2)、带条件的查询
查询title为huaibei的字段
1$query=array(”title”=>”huaibei”);
2$cursor=$collection->find($query);//在$collectio集合中查找满足$query的文档
常用的SQL转化为mongodb的条件
复制代码代码示例:
mysql:id=123
mongo:array(‘id’=>123)
mysql:namelink’%bar%’
mongo:array(‘name’=>newMongoRegex(‘/.*bar.*/i’))
mysql:whereid>10
mongo:array(‘id’=>array(‘$gt’=>10))
mysql:whereid>=10
mongo:array(‘id’=>array(‘$gte’=>10))
mysql:whereid<10
mongo:array(‘id’=>array(‘$lt’=>10))
mysql:whereid<=10
mongo:array(‘id’=>array(‘$lte’=>10))
mysql:whereid>1andid<10
mongo:array(‘id’=>array(‘$gt’=>1,’$lt’=>10))
mysql:whereid<>10
mongo:array(‘id’=>array(‘$ne’=>10))
mysql:whereidin(123)
mongo:array(‘id’=>array(‘$in’=>array(1,2,3)))
mysql:whereidnotin(123)
mongo:array(‘id’=>array(‘$nin’=>array(1,2,3)))
mysql:whereid=2orid=9
mongo:array(‘id’=>array(‘$or’=>array(array(‘id’=>2),array(‘id’=>9))))
mysql:orderbynameasc
mongo:array(‘sort’=>array(‘name’=>1))
mysql:orderbynamedesc
mongo:array(‘sort’=>array(‘name’=>-1))
mysql:limit0,2
mongo:array(‘limit’=>array(‘offset’=>0,’rows’=>2))
mysql:selectname,email
mongo:array(‘name’,'email’)
mysql:selectcount(name)
mongo:array(‘COUNT’)//注意:COUNT为大写
更详细的转换参考http://us2.php.net/manual/en/mongo.sqltomongo.php
注意事项:
查询时,每个Object插入时都会自动生成一个独特的_id,它相当于RDBMS中的主键,用于查询时非常方便(_id每一都不同,很像自动增加的id)
例如:
复制代码代码示例:
<?php
$param=array("name"=>"joe");
$collection->insert($param);
$joe=$collection->findOne(array("_id"=>$param['_id']));
print_R($joe);
$m->close();
返回结果:Array([_id]=>MongoIdObject([$id]=>4fd30e21870da83416000002)[name]=>joe)
更改字段值:
复制代码代码示例:
<?php
$sign=array("title"=>'php1');
$param=array("title"=>'php1','author'=>'test');
$joe=$collection->update($sign,$param);
删除一个数据库:
复制代码代码示例:
$m->dropDB(“comedy”);
列出所有可用数据库:
复制代码代码示例:
$m->listDBs();//无返回值
附,mongodb常用的数据库方法
MongoDB中有用的函数:
创建一个MongoDB对象
复制代码代码示例:
<?php
$mo=newMongo();
$db=newMongoDB($mo,’dbname’);//通过创建方式获得一个MongoDB对象
删除当前DB
复制代码代码示例:
<?php
$db=$mo->dbname;
$db->drop();
获得当前数据库名
复制代码代码示例:
<?php
$db=$mo->dbname;
$db->_tostring();
选择想要的collection:
复制代码代码示例:
A:
$mo=newMongo();
$coll=$mo->dbname->collname;//获得一个collection对象
B:
$db=$mo->selectDB(’dbname’);
$coll=$db->collname;
C:
$db=$mo->dbname;
$coll=$db->collname;
D:
$db=$mo->dbname;
$coll=$db->selectCollectoin(’collname’);//获得一个collection对象
插入数据(MongoCollection对象):
http://us.php.net/manual/en/mongocollection.insert.php
MongoCollection::insert(array$a,array$options)
array$a要插入的数组
array$options选项
safe是否返回操作结果信息
fsync是否直接插入到物理硬盘
例子:
复制代码代码示例:
$coll=$mo->db->foo;
$a=array(’a’=>’b’);
$options=array(’safe’=>true);
$rs=$coll->insert($a,$options);
$rs为一个array型的数组,包含操作信息
删除数据库中的记录(MongoCollection对象):
http://us.php.net/manual/en/mongocollection.remove.php
MongoCollection::remove(array$criteria,array$options)
array$criteria条件
array$options选项
safe是否返回操作结果
fsync是否是直接影响到物理硬盘
justOne是否只影响一条记录
例子:
复制代码代码示例:
$coll=$mo->db->coll;
$c=array(’a’=>1,’s’=>array(’$lt’=>100));
$options=array(’safe’=>true);
$rs=$coll->remove($c,$options);
$rs为一个array型的数组,包含操作信息
更新数据库中的记录(MongoCollection对象):
http://us.php.net/manual/en/mongocollection.update.php
MongoCollection::update(array$criceria,array$newobj,array$options)
array$criteria条件
array$newobj要更新的内容
array$options选项
safe是否返回操作结果
fsync是否是直接影响到物理硬盘
upsert是否没有匹配数据就添加一条新的
multiple是否影响所有符合条件的记录,默认只影响一条
例子:
复制代码代码示例:
$coll=$mo->db->coll;
$c=array(’a’=>1,’s’=>array(’$lt’=>100));
$newobj=array(’e’=>’f’,’x’=>’y’);
$options=array(’safe’=>true,’multiple’=>true);
$rs=$coll->remove($c,$newobj,$options);
$rs为一个array型的数组,包含操作信息
查询collection获得单条记录(MongoCollection类):
http://us.php.net/manual/en/mongocollection.findone.php
arrayMongoCollection::findOne(array$query,array$fields)
array$query条件
array$fields要获得的字段
例子:
复制代码代码示例:
$coll=$mo->db->coll;
$query=array(’s’=>array(’$lt’=>100));
$fields=array(’a’=>true,’b’=>true);
$rs=$coll->findOne($query,$fields);
如果有结果就返回一个array,如果没有结果就返回NULL
查询collection获得多条记录(MongoCollection类):
http://us.php.net/manual/en/mongocollection.find.php
MongoCursorMongoCollection::find(array$query,array$fields)
array$query条件
array$fields要获得的字段
例子:
复制代码代码示例:
$coll=$mo->db->coll;
$query=array(’s’=>array(’$lt’=>100));
$fields=array(’a’=>true,’b’=>true);
$cursor=$coll->find($query,$fields);
//排序
$cursor->sort(array(‘字段’=>-1));(-1倒序,1正序)
//跳过部分记录
$cursor->skip(100);跳过100行
//只显示部分记录
$cursor->limit(100);只显示100行
返回一个游标记录对象MongoCursor。
针对游标对象MongoCursor的操作(MongoCursor类):
http://us.php.net/manual/en/class.mongocursor.php
循环或结果记录:
复制代码代码示例:
$cursor=$coll->find($query,$fields);
while($cursor->hasNext()){
$r=$cursor->getNext();
var_mp($r);
}
或者
$cursor=$coll->find($query,$fields);
foreache($cursoras$k=>$v){
var_mp($v);
}
或者
$cursor=$coll->find($query,$fields);
$array=iterator_to_array($cursor);
⑽ mongodb查找所有最多
方法一:对目标值按大到小排序后,再取出第一条
具体查询语句是
db.getCollection('collection1').find().sort({ rid: -1}).limit(1)
在Robo 3T中运行,有10万条数据集中,查询时间为0.002s
方法二:用aggregate的group结合max
具体查询语句是
1|db.getCollection('collection1').aggregate([{$group:{"_id": "$id","max_rid":{$max: "$rid"}}}])
在Robo 3T中运行,有10万条数据集中,查询时间为0.908s
查询性能明显没有方法一高效。
总结:故生产环境中应选用方法一。
MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。