迭代大型 mongodb 集合以更新架构
iterate over large mongodb collection for purpose of updating schema
我收集了 30 万份测试文档。我想将所有人 firstName
和 lastName
更新为小写。
const person = new Schema({
firstName: { type: String},
lastName: { type: String }
})
我已将 lowecase:true
添加到架构中,但如何更新现有文档?
我试过了:
CaseFile
.find({ })
.cursor()
.eachAsync(async function (doc) {
await doc.save()
})
但我收到错误
Error: Collection method find is synchronous
我也试过了:
CaseFile
.find({ })
.then(docs => {
docs.forEach(doc => {
doc.save()
})
})
给出错误:
JavaScript heap out of memory
数据库版本v5.0.2
"猫鼬": "^6.0.5",
感谢 Wernfried Domscheit 提供管道解决方案:
CaseFile.updateMany({}, [
{
$set:
{
firstName: { $toLower: '$firstName' },
lastName: { $toLower: '$lastName' }
}
}]
)
.then(res => res)
到底为什么要“迭代”,即逐行迭代?
使用聚合管道:
db.CaseFile.updateMany({}, [
{ $set:
firstName: { $toLower: "$firstName" },
lastName: { $toLower: "$lastName" }
}
])
我收集了 30 万份测试文档。我想将所有人 firstName
和 lastName
更新为小写。
const person = new Schema({
firstName: { type: String},
lastName: { type: String }
})
我已将 lowecase:true
添加到架构中,但如何更新现有文档?
我试过了:
CaseFile
.find({ })
.cursor()
.eachAsync(async function (doc) {
await doc.save()
})
但我收到错误
Error: Collection method find is synchronous
我也试过了:
CaseFile
.find({ })
.then(docs => {
docs.forEach(doc => {
doc.save()
})
})
给出错误:
JavaScript heap out of memory
数据库版本v5.0.2
"猫鼬": "^6.0.5",
感谢 Wernfried Domscheit 提供管道解决方案:
CaseFile.updateMany({}, [
{
$set:
{
firstName: { $toLower: '$firstName' },
lastName: { $toLower: '$lastName' }
}
}]
)
.then(res => res)
到底为什么要“迭代”,即逐行迭代?
使用聚合管道:
db.CaseFile.updateMany({}, [
{ $set:
firstName: { $toLower: "$firstName" },
lastName: { $toLower: "$lastName" }
}
])