⑴ 求助安裝 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最大的特點是它支持的查詢語言非常強大,其語法有點類似於面向對象的查詢語言,幾乎可以實現類似關系資料庫單表查詢的絕大部分功能,而且還支持對數據建立索引。