gpt4 book ai didi

mongodb更新大型集合数组中的对象

转载 作者:可可西里 更新时间:2023-11-01 10:46:51 25 4
gpt4 key购买 nike

假设我想一键更新数千个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'
})
})
})

我知道更好的主意是创建一个额外的“仪器”模型,但后来我无法搜索包含某些仪器的 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...

您可以在 Job 中按引用数组的 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更新大型集合数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49680448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com