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

  • \u0022 is the Unicode escape sequence for double quotes (")
  • MongoDB automatically converts \u0022 to 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.

Updated on: 2026-03-15T00:59:18+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements