你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

$type(元素查询)

适用对象: MongoDB vCore

如果字段的类型为指定类型,则 $type 运算符选择文档。 这对于数据验证和确保集合中文档的一致性非常有用。 运算符 $type 接受 BSON 类型号和字符串别名。

语法

运算符的 $isArray 语法如下所示:

{
  <field>: { $type: <BSON type number> | <string alias> }
}

参数

DESCRIPTION
field 要检查其类型的字段。
BSON type number 对应于 BSON 类型的数字(例如,1 表示双精度,字符串为 2)。
string alias BSON 类型的字符串别名(例如“double”、“string”、“object”、“array”)。

常见 BSON 类型

类型 编号 别名 DESCRIPTION
加倍 1 “double” 64 位浮点
字符串 2 “string” UTF-8 字符串
物体 3 “object” 嵌入的文档
数组 4 “array” 数组
对象标识符 (ObjectId) 7 “objectId” 对象标识符 (ObjectId)
布尔型 8 “bool” 布尔型
日期 9 “date” 日期
10 “null” 空值
32位整数 16 “int” 32位整数
时间戳 十七 “timestamp” 时间戳
64 位整数 18 “long” 64 位整数

示例:

让我们了解数据集中示例 JSON 的 stores 用法。

{
  "_id": "905d1939-e03a-413e-a9c4-221f74055aac",
  "name": "Trey Research | Home Office Depot - Lake Freeda",
  "location": { "lat": -48.9752, "lon": -141.6816 },
  "staff": { "employeeCount": { "fullTime": 12, "partTime": 19 } },
  "sales": {
    "salesByCategory": [ { "categoryName": "Desk Lamps", "totalSales": 37978 } ],
    "revenue": 37978
  },
  "promotionEvents": [
    {
      "eventName": "Crazy Deal Days",
      "promotionalDates": {
        "startDate": { "Year": 2023, "Month": 9, "Day": 27 },
        "endDate": { "Year": 2023, "Month": 10, "Day": 4 }
      },
      "discounts": [
        { "categoryName": "Desks", "discountPercentage": 22 },
        { "categoryName": "Filing Cabinets", "discountPercentage": 23 }
      ]
    }
  ],
  "company": "Trey Research",
  "city": "Lake Freeda",
  "storeOpeningDate": "2024-09-26T22:55:25.779Z",
  "lastUpdated": "Timestamp({ t: 1729983325, i: 1 })"
}

示例 1:查找具有字符串类型名称的存储

该示例查找字段为字符串类型的所有存储 name

db.stores.find(
 { "name": { $type: "string" }},
 { "_id": 1, "name": 1 }).limit(1)

查询返回字段 name 包含字符串值的所有文档。

{
  "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6",
  "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort"
}

示例 2:使用多个类型检查进行数据验证

此示例演示如何验证基本字段是否具有正确的数据类型。

db.stores.find({
  "_id": "905d1939-e03a-413e-a9c4-221f74055aac",
  "name": { $type: "string" },
  "location": { $type: "object" },
  "staff.employeeCount.fullTime": { $type: ["int", "long"] },
  "promotionEvents": { $type: "array" }},
  { "_id": 1, "name": 1,"location":1, "staff": 1 }
)

查询将返回所有指定字段具有预期数据类型的存储,帮助确保数据一致性。

{
  "_id": "905d1939-e03a-413e-a9c4-221f74055aac",
  "name": "Trey Research | Home Office Depot - Lake Freeda",
  "location": { "lat": -48.9752, "lon": -141.6816 },
  "staff": { "employeeCount": { "fullTime": 12 } }
}