1.基础数据如下
db.test1.insert(
{
"name" : "这是一个测试数据有空格 ",
"type" : "A001",
"createTime" : ISODate("2023-07-22T10:10:31.087+08:00"),
"updateTime" : ISODate("2023-07-22T10:10:31.087+08:00")
}
)
![如何去除MongoDB集合字段值末尾空格并提升数据质量_处理方法](//dev-img.mos.moduyun.com/20231113/03c46c09-69a7-4c86-b54a-9e702d46b637.jpg)
2.在mongodb3.4版本中的处理方法
db.test1.find().forEach(function(doc) {
var trimmedName = doc.name.trim();
if (trimmedName !== doc.name) {
db.test1.update(
{ _id: doc._id },
{ $set: { name: trimmedName } }
);
}
});
![如何去除MongoDB集合字段值末尾空格并提升数据质量_mongodb_02](//dev-img.mos.moduyun.com/20231113/c27e50e4-9740-40bb-b800-63f5cc9d6f8b.jpg)
3.在mongodb6.0版本中的处理方法
db.test1.update(
{ },
{ $set: { name: { $trim: { input: "$name" } } } },
{ multi: true }
)