iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 13
0
AI & Data

從入門到精通 MongoDB系列 第 13

Day13: 進階的 CRUD 操作(3) - 比較和邏輯查詢運算子

在之前「Day05: MongoDB 的 CRUD(3) - Find & Update」這篇文章中曾使用到 比較查詢運算子 $gt 來做進階的資料查詢,接下來三篇將會介紹在 MongoDB 中使用的運算子:比較查詢運算子、邏輯查詢運算子、元素查詢運算子及 Array 查詢運算子。


運算子


對資料進行簡單的查詢操作時,我們只會使用 method 加上 filters 進行查詢,例如要查詢「年齡是20歲」的人,只需要使用 db.collection.find( {age: 20} )。但若要查詢「年齡超過20歲」的人,則需要使用較複雜的 filters:db.collection.find( {age: {$gt: 20}} ),比起第一個查詢,多了 $gt 這個 operator 運算子

運算子的種類

  1. Query 和 Projection:查找和返回值修整
    • 用於過濾資料,和修改返回值的表現形式
  2. Update:更新
    • 用於修改資料庫中的具體資料
  3. Aggregation:聚合
    • 用於聚合的 pipeline

比較查詢運算子

如我們之前使用過的 $gt ,比較運算子是用來比較值的大小,有以下幾種比較運算子:

  • $eq:等於
    • db.inventory.find( {tags : {$eq : ['A', 'B']}} )
    • 也可以直接寫成:db.inventory.find( {tags : ['A', 'B']} )
  • $gt:大於
  • $gte:大於等於
  • $in:包含其中任意一個
    • db.inventory.find( {price : {$in : [5, 15]}} ):價格為5或15的庫存
  • $lt:小於
  • $lte:小於等於
  • $ne:不等於
    • db.inventory.find( {price : {$ne : 20}} ):價格不是20的庫存
  • $nin:不包含其中任意一個
    • db.inventory.find( {price : {$nin : [5, 15]}} ):價格不是5也不是15的庫存

我們直接來用以下範例來介紹這些比較查詢運算子:

範例資料:movie.json

[
    {
        "title": "Avatar",
        "year": 2009,
        "director_name": "James Cameron",
        "actors": [
            "CCH Pounder",
            "Joel David Moore"
        ],
        "duration": 178,
        "country": "USA",
        "content_rating": "PG-13",
        "gross": 760505847,
        "imdb_score": 7.9
    },
	
    ...
	
    {
        "title": "The Hobbit: An Unexpected Journey",
        "year": 2012,
        "director_name": "Peter Jackson",
        "actors": [
            "Aidan Turner",
            "Adam Brown"
        ],
        "duration": 182,
        "country": "USA",
        "content_rating": "PG-13",
        "gross": 303001229,
        "imdb_score": 7.9
    }
]
  • 導入範例資料:mongoimport /Users/andylin/Documents/resource/courses/mongodb/movie.json -d demo -c movie --jsonArray --drop

  • 用 findOne() 檢視

練習1:查詢 imdb_score > 8 的電影

  • db.movie.find({imdb_score: {$gt: 8}})
  • 共有 12 部

練習2:查詢 imdb_score < 7 的電影

  • db.movie.find({imdb_score: {$lt: 7}})
  • 共有 49 部

練習3:查詢 imdb_score = 7 的電影

  • 方法一:db.movie.find({imdb_score: {$eq: 7}}).count()
  • 方法二:db.movie.find({imdb_score: 7}).count()

練習4:查詢演員名單包含 Johnny Depp 的電影

  • db.movie.find({actors: {$in: ["Johnny Depp"]}}).pretty()
  • 共有 5 部

練習5:查詢演員名單不包含 Johnny Depp 的電影

  • db.movie.find({actors: {$nin: ["Johnny Depp"]}}).pretty()
  • 共有 95 部

邏輯查詢運算子

邏輯查詢運算子是用來做一些邏輯判斷,有以下幾種邏輯查詢運算子:

  • $and:邏輯和
    • db.inventory.find( {$and: [{price: {$ne: 1.99}} , {price: {$exists: true}}]} )
  • $not:邏輯非
    • db.inventory.find( {price {$not {$gt: 1.99}}} )
  • $nor:邏輯或的反義
    • db.inventory.find( {$nor: [{price: 1.99}, {sale: true}]} )
  • $or:邏輯或
    • db.inventory.find( {$or: [{quantity: {$lt: 20}}, {price: 10}]} )

練習1:查詢 imdb_score 大於 7 且小於 8 的電影

  • db.movie.find({$and: [{imdb_score: {$gt: 7}} , {imdb_score: {$lt: 8}}]})
  • 共有 32 部

練習2:查詢 imdb_score 大於 7 的電影

  1. 方法1:db.movie.find({imdb_score: {$gt: 7}}).count()

  2. 方法2:db.movie.find({imdb_score: {$not: {$lte: 7}}}).count()

練習3:查詢 imdb_score 小於 7 或大於 8 的電影

  • db.movie.find({$or: [{imdb_score: {$lt: 7}} , {imdb_score: {$gt: 8}}]})
  • 共有 61 部

練習4:查詢 imdb_score 大於等於 7 且小於等於 8 的電影

  • 練習四:查詢 imdb_score 大於等於 7 且小於等於 8 的電影
  • 共有 39 部

今天介紹了比較查詢運算子及邏輯查詢運算子,可以用來做進階的過濾查詢,下一篇會接著介紹元素查詢運算子。


上一篇
Day12: 進階的 CRUD 操作(2) - 如何透過 JSON 文件導入資料
下一篇
Day14: 進階的 CRUD 操作(4) - 元素查詢運算子
系列文
從入門到精通 MongoDB26
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言