MongoDB原生支持UTF-8编码,这意味着它可以直接存储和处理中文字符。要确保中文正常显示,主要需要关注三个环节:数据库编码设置、客户端连接配置和应用程序处理。
mongod --setParameter enableLocalhostAuthBypass=1 --setParameter disableJavaScriptProtection=1
use mydb
db.createCollection('mycollection', { collation: { locale: 'zh' } })
确保终端或命令行工具支持UTF-8编码:
chcp 65001 # Windows系统设置UTF-8编码
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
connectTimeoutMS: 30000,
socketTimeoutMS: 30000
});
db.products.insertOne({
name: "中文商品名称",
description: "这是商品的中文描述",
price: 99.9
})
db.products.find({ name: /中文/ })
解决方案:确保所有环节统一使用UTF-8编码
db.products.find().collation({ locale: 'zh' }).sort({ name: 1 })
db.products.createIndex({ description: "text" })
db.products.find({ $text: { $search: "中文" } })