ใช้ Unicode Escape Sequence \u0022 สำหรับ Double Quote ใน String
ใน MongoDB Shell (JavaScript) สตริงใช้ Single Quote หรือ Double Quote หากต้องการใส่ Double Quote ลงใน String ที่อยู่ใน Double Quote ต้อง Escape ด้วย Backslash หรือใช้ Unicode
วิธีการ: ใช้ \u0022 (Unicode สำหรับ ")
> db.escapingQuotesDemo.insert({ "StudentFullName": "John \u0022 Smith" });
WriteResult({ "nInserted" : 1 })
> db.escapingQuotesDemo.insert({ "StudentFullName": "David \u0022 Miller" });
WriteResult({ "nInserted" : 1 })
> db.escapingQuotesDemo.insert({ "StudentFullName": "John \u0022 Doe" });
WriteResult({ "nInserted" : 1 })
> db.escapingQuotesDemo.insert({ "StudentFullName": "Carol \u0022 Taylor" });
WriteResult({ "nInserted" : 1 })
ผลลัพธ์: Double Quote ถูกเก็บในข้อมูลจริง
> 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" }
วิธี Escape อื่นๆ ใน MongoDB Shell (JavaScript)
| อักขระ | Escape Sequence | Unicode | ตัวอย่าง |
|---|---|---|---|
| Double Quote (") | \" | \u0022 | "He said \"Hi\"" |
| Single Quote (') | \' | \u0027 | 'It\'s mine' |
| Backslash (\) | \\ | \u005C | "C:\\Path\\File" |
| Newline | \n | \u000A | "Line1\nLine2" |
| Tab | \t | \u0009 | "Col1\tCol2" |