Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Escaping quotes while inserting records in MongoDB?
To escape quotes while inserting records in MongoDB, use the Unicode escape sequence \u0022 to represent double quotes within string values. This prevents syntax errors when quotes are part of the data content.
Syntax
db.collection.insertOne({
"fieldName": "text with \u0022 escaped quotes \u0022"
});
Sample Data
Let us create a collection with documents containing escaped quotes in student names ?
db.escapingQuotesDemo.insertMany([
{ "StudentFullName": "John \u0022 Smith" },
{ "StudentFullName": "David \u0022 Miller" },
{ "StudentFullName": "John \u0022 Doe" },
{ "StudentFullName": "Carol \u0022 Taylor" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("..."),
ObjectId("..."),
ObjectId("..."),
ObjectId("...")
]
}
Verify Results
Display all documents to see how the escaped quotes are stored ?
db.escapingQuotesDemo.find().pretty();
{
"_id" : ObjectId("5ccf42e2dceb9a92e6aa195b"),
"StudentFullName" : "John " Smith"
}
{
"_id" : ObjectId("5ccf42f0dceb9a92e6aa195c"),
"StudentFullName" : "David " Miller"
}
{
"_id" : ObjectId("5ccf42f9dceb9a92e6aa195d"),
"StudentFullName" : "John " Doe"
}
{
"_id" : ObjectId("5ccf4303dceb9a92e6aa195e"),
"StudentFullName" : "Carol " Taylor"
}
Key Points
-
\u0022is the Unicode escape sequence for double quotes (") - MongoDB automatically converts
\u0022to actual quote characters when storing data - This method prevents JSON parsing errors when quotes are part of the field value
Conclusion
Use Unicode escape sequence \u0022 to safely insert quotes within MongoDB string values. The database automatically converts these escape sequences to actual quote characters during storage.
Advertisements
