參考官方文檔(圖文並茂非常好看):Getting Started - MongoDB Documentation
MongoDB的查詢功能非常強大,同時有些地方也會有點複雜。所以需要下點功夫學習和操練才能用好。
關於Mongo Shell
當我們進入Mongo Shell
客戶端後,實際上是進入了一個Javascript語言
的交互環境。
也就是說,MongoDB中的很多命令,尤其是包括定義函數等高級命令,實際上都是Javascript語言,甚至說可以是jQuery
。
瞭解了這點,一些高級命令如Aggregation學起來就會放鬆很多。
官方說明:
基本查詢功能
比較運算
-
:
等於 -
$lt
: Less Than -
$gt
: Greater Than -
$gte
: Greater Than or Equal -
$ne
: Not Equal
# age大於等於18
db.mycollection1.find( { age:{$gt: 18} } )
邏輯運算
$and
$or
db.mycollection1.find( {
$or: [
{ age: {$gte: 20} },
{ salary: {$gt: 5000} },
{ job: "HR" }
]
} )
範圍運算
$in
-
$nin
: Not In
db.mycollection1.find( {
age: {
$in: [10, 20, 30]
}
} )
正則表達式
有兩種方法:
/表達式內容/
{$regex: "表達式內容"}
db.mycollection1.find( {
name: /^Ja\w+$/
} )
# 或
db.mycollection1.find( {
name: {
$regex: "/^Jaso\w?$"
}
} )
limit和skip
# 限定顯示條數
db.mycollection1.find().limit(數量)
# 跳過指定第幾條數據
db.mycollection1.find().skip(2)
# 混合使用
db.mycollection1.find().limit(10).skip(3)
自定義函數查詢
自定義查詢是指使用自定義函數,格式爲$where: function(){...}
db.mycollection1.find( {
$where: function() {
return this.age >= 18;
}
} )
投影
即搜索的返回值中,只顯示指定的某些字段。字段指爲0的不現實,指爲1的顯示,默認爲1。
# 格式爲:
db.mycollection1.find(
{查詢條件},
{顯示與否的選項}
)
# 如:
db.mycollection1.find(
{},
{ _id: 0, name: 1, age: 1 }
)
排序
可以按指定的某些字段排序,字段標記爲1的爲Asc升序,標記爲-1的爲Desc降序。
db.mycollection1.find().sort({ name:1, age:-1 })
統計
使用count()函數。
db.mycollection1.find().count()
db.mycollection1.count( {查詢條件} )
消除重複
使用distinct()函數。
# 格式爲:
db.集合名.distinct( "指定字段", {查詢條件} )
# 如
db.mycollection1.distinct(
"job",
{ age: {$lt: 40} }
)
聚合管道 Aggregation
Aggregation是MongoDB特有的一種Pipline管道型、聚合查詢方式。語法稍微複雜一些。
聚合管道可以達到多步驟的分組、篩選功能。這個管道中的每一個步驟,成爲一個stage
。
常用的管道有:
-
$match
:簡單的根據條件過濾篩選 -
$group
:將數據分組,一般配合一些統計函數,如$sum
。 -
$project
:修改document的結構。如增刪改,或創建計算結果 -
$lookup
: -
$unwind
:將List列表類型的Document進行拆分 $sort
$limit
$skip
語法格式爲:
db.集合名.aggregate( [
{管道表達式1},
{管道表達式2},
{管道表達式2}
] )
示例:
db.Orders.aggregate( [
{$match: {
status: "A"
} },
{$group: {
_id: "$cut_id",
total: { $sum: "$amount" }
} }
] )
管道的Map Reduce