文字列データの処理
このステップでは、MongoDB で文字列型のデータを扱う方法を学び、データベースに文字列を格納、照会、操作するさまざまな方法を探ります。
MongoDB の文字列型を理解する
MongoDB は強力な文字列処理機能を備えています。前のステップで作成したデータベースを引き続き使用して、文字列操作を示します。
まず、MongoDB シェルにいることを確認します。
mongosh
既存のデータベースに切り替えます。
use numbers_lab
文字列データの挿入と照会
文字列フィールドを持つドキュメントを追加しましょう。
db.products.insertMany([
{
name: "Wireless Headphones",
brand: "TechSound",
description: "High-quality noise-canceling headphones",
color: "Black",
tags: ["electronics", "audio", "wireless"]
},
{
name: "Smart Watch",
brand: "FitTech",
description: "Advanced fitness tracking smartwatch",
color: "Silver",
tags: ["wearables", "fitness", "technology"]
}
])
文字列照会操作
MongoDB は文字列データを照会するさまざまな方法を提供しています。
// 正確な名前で商品を検索
db.products.find({ name: "Smart Watch" })
// 正規表現を使用した大文字小文字を区別しない検索
db.products.find({ brand: { $regex: /tech/i } })
// タグの配列内で検索
db.products.find({ tags: "electronics" })
文字列操作メソッド
文字列操作も行うことができます。
// 説明を更新
db.products.updateOne(
{ name: "Wireless Headphones" },
{ $set: { description: description.toUpperCase() } }
)
// 文字列の長さを確認
db.products.find({
$expr: { $gt: [{ $strLenCP: "$name" }, 10] }
})
覚えておくべきポイント
- MongoDB の文字列は UTF-8 でエンコードされています
- パターンマッチングには
$regex
を使用します
- 配列には文字列要素を含めることができます
- MongoDB はさまざまな文字列操作メソッドをサポートしています