Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

Escape Quotes (อักขระเครื่องหมายคำพูด) ขณะ Insert ใน MongoDB

ใช้ 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)

Best Practice

  • ใน Application Code (Node.js, Python, Java ใช้ Driver) - ไม่ต้อง Escape เอง Driver จัดการให้
  • ใน Mongo Shell - ใช้ Single Quote ครอบ String ที่มี Double Quote: 'John "Smith"'
  • ใช้ Unicode Escape (\u0022) เมื่อต้อง Double Quote ครอบ และมี Double Quote อยู่ใน
  • JSON ไฟล์ Import ด้วย mongoimport - ต้องเป็น Valid JSON (Escape ด้วย Backslash)
อักขระEscape SequenceUnicodeตัวอย่าง
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"