mongodb 更新大型集合数组中的对象
mongodb update objects inside arrays of large collection
说我想一键更新上千个mongodb模型,会不会运行出现意想不到的问题?这个想法是一旦有第三种语言添加到 webapp 就更新所有条目。
型号:
JobSchema = new mongoose.Schema({
info:{
instruments:[{
index:String,
de:String,
en:String,
}],
},
});
自定义更新(数千个结果):
Job.find({}, function(err, foundJobs){
//no error handling for the sake of simplicity
foundJobs.forEach(function(job){
job.info.instruments.forEach(function(instr, index){
instr.en = 'FOO'
})
})
})
我知道更好的主意是创建一个额外的 "Instrument" 模型,但后来我无法搜索包含某些仪器的 JobModels...至少我找不到好的方法... .
试试这个...
Job.updateMany({},
{ $set: { instruments.$.en: 'FOO' }, (err, result) => {
if (err) {
next(err);
} else {
res.status(200).json(result);
}
});
I know the better idea would be to create an extra "Instrument" model, but then I couldn't search for JobModels containing certain instruments...at least I couldn't find a good method...
您可以在作业中按引用数组的 ID 进行搜索。
JobSchema = new mongoose.Schema({
info:{
instruments: [{type: mongoose.Schema.Types.ObjectId, ref: 'Instrument'}],
}
});
InstrumentSchema = new mongoose.Schema({
index:String,
de:String,
en:String
});
// assuming instrumentIDs is an array containing instrument object IDs.
JobSchema.find({ info.instruments: {$all : instrumentIDs } })
恕我直言,如果您描述的更新在满月时发生一次,则不值得对其进行标准化。
说我想一键更新上千个mongodb模型,会不会运行出现意想不到的问题?这个想法是一旦有第三种语言添加到 webapp 就更新所有条目。
型号:
JobSchema = new mongoose.Schema({
info:{
instruments:[{
index:String,
de:String,
en:String,
}],
},
});
自定义更新(数千个结果):
Job.find({}, function(err, foundJobs){
//no error handling for the sake of simplicity
foundJobs.forEach(function(job){
job.info.instruments.forEach(function(instr, index){
instr.en = 'FOO'
})
})
})
我知道更好的主意是创建一个额外的 "Instrument" 模型,但后来我无法搜索包含某些仪器的 JobModels...至少我找不到好的方法... .
试试这个...
Job.updateMany({},
{ $set: { instruments.$.en: 'FOO' }, (err, result) => {
if (err) {
next(err);
} else {
res.status(200).json(result);
}
});
I know the better idea would be to create an extra "Instrument" model, but then I couldn't search for JobModels containing certain instruments...at least I couldn't find a good method...
您可以在作业中按引用数组的 ID 进行搜索。
JobSchema = new mongoose.Schema({
info:{
instruments: [{type: mongoose.Schema.Types.ObjectId, ref: 'Instrument'}],
}
});
InstrumentSchema = new mongoose.Schema({
index:String,
de:String,
en:String
});
// assuming instrumentIDs is an array containing instrument object IDs.
JobSchema.find({ info.instruments: {$all : instrumentIDs } })
恕我直言,如果您描述的更新在满月时发生一次,则不值得对其进行标准化。