Handle String Data
In this step, you'll learn how to work with string data types in MongoDB, exploring different ways to store, query, and manipulate text data in your database.
Understanding String Types in MongoDB
MongoDB provides powerful string handling capabilities. We'll continue using the database we created in the previous step to demonstrate string operations.
First, ensure you're in the MongoDB shell:
mongosh
Switch to the existing database:
use numbers_lab
Inserting and Querying String Data
Let's add more documents with string fields:
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"]
}
])
String Query Operations
MongoDB offers various ways to query string data:
// Find products by exact name
db.products.find({ name: "Smart Watch" })
// Case-insensitive search using regex
db.products.find({ brand: { $regex: /tech/i } })
// Search in array of tags
db.products.find({ tags: "electronics" })
String Manipulation Methods
You can also perform string operations:
// Update description
db.products.updateOne(
{ name: "Wireless Headphones" },
{ $set: { description: description.toUpperCase() } }
)
// Check string length
db.products.find({
$expr: { $gt: [{ $strLenCP: "$name" }, 10] }
})
Key Points to Remember
- Strings in MongoDB are UTF-8 encoded
- Use
$regex
for pattern matching
- Arrays can contain string elements
- MongoDB supports various string manipulation methods