iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 14
0
AI & Data

從入門到精通 MongoDB系列 第 14

Day14: 進階的 CRUD 操作(4) - 元素查詢運算子

在上一篇文章中介紹了 比較查詢運算子邏輯查詢運算子 ,今天接著來介紹 元素查詢運算子 Element Query Operators


元素查詢運算子

元素查詢運算子有以下兩種:

  • $exists:判斷 document 是否存在特定 field
  • $type:判斷某個 field 的資料型態是否為某種 BSON type

$exists 存在

我們直接透過一個範例來介紹 $exists 這個元素查詢運算子。

範例:

判斷 inventory 這個 collection 中是否存在 qty 這個欄位 並且 qty 欄位的值不等於5或15

  • db.inventory.find( { qty: { $exists: true, $nin: [ 5, 15 ] } } )

$type 資料型態

官方文檔裡我們可以看到 $type 接受以下的 BSON 資料型態:

Type Number Alias
Double 1 "double"
String 2 "string"
Object 3 "object"
Array 4 "array"
Binary data 5 "binData"
Undefined 6 "undefined"
ObjectId 7 "objectId"
Boolean 8 "bool"
Date 9 "date"
Null 10 "null"
Regular Expression 11 "regex"
DBPointer 12 "dbPointer"
Javascript 13 "javascript"
Symbol 14 "symbol"
Javascript(with scope) 15 "javascriptWithScope"
32-bit integer 16 "int"
Timestamp 17 "timestamp"
64-bit integer 18 "long"
Decimal128 19 "decimal"
Min key -1 "minKey"
Max key 127 "maxKey"

我們一樣直接透過以下範例來介紹 $type 這個元素查詢運算子。

範例資料:

[
    { "_id" : 1, address : "2030 Martian Way", zipCode : "90698345" },
    { "_id" : 2, address: "156 Lunar Place", zipCode : 43339374 },
    { "_id" : 3, address : "2324 Pluto Place", zipCode: NumberLong(3921412) },
    { "_id" : 4, address : "55 Saturn Ring" , zipCode : NumberInt(88602117) },
    { "_id" : 5, address : "104 Venus Drive", zipCode : ["834847278", "1893289032"]}
]

範例1:查詢 zipCode 是字串 string 的地址

  • 方法1:db.addressBook.find( { "zipCode" : { $type : 2 } } )
  • 方法2:db.addressBook.find( { "zipCode" : { $type : "string" } } )
  • 回傳結果:
{ "_id" : 1, "address" : "2030 Martian Way", "zipCode" : "90698345" }
{ "_id" : 5, "address" : "104 Venus Drive", "zipCode" : [ "834847278", "1893289032" ] }

範例2:查詢 zipCode 是 double 的地址

  • 方法1:db.addressBook.find( { "zipCode" : { $type : 1 } } )
  • 方法2:db.addressBook.find( { "zipCode" : { $type : "double" } } )
  • 回傳結果:
{ "_id" : 2, "address" : "156 Lunar Place", "zipCode" : 43339374 }

今天簡單介紹了元素查詢運算子,可以透過 $exists$type 來查詢特定元素的結果。明天會介紹最後一種查詢運算子:佇列查詢運算子 Array Query Operators


上一篇
Day13: 進階的 CRUD 操作(3) - 比較和邏輯查詢運算子
下一篇
Day15: 進階的 CRUD 操作(5) - Array 相關查詢運算子
系列文
從入門到精通 MongoDB26
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言