mongo执行逻辑表达式_MongoDB 高级查询
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
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的mongo执行逻辑表达式_MongoDB 高级查询的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: max格式转obj小工具_Python写
- 下一篇: dqs server sql_SQL-S