Mongodb 我想知道如何为Mongo DB编写更新脚本
我想知道如何编写mongodb脚本来更新数据库中的字段 我的收藏是这样的Mongodb 我想知道如何为Mongo DB编写更新脚本,mongodb,Mongodb,我想知道如何编写mongodb脚本来更新数据库中的字段 我的收藏是这样的 { _id: 1, name: xyz, answer: [ { type: 'C', from: 0 }, { type: 'M', from: 0 }, { type: 'P', from: 0
{
_id: 1,
name: xyz,
answer: [
{ type: 'C',
from: 0
},
{ type: 'M',
from: 0
},
{ type: 'P',
from: 0
}
........ so on
]
}
.
.
.
and other objects
我想在应答数组的每个对象中添加一个名为“test”的字段,其“type”值不是“C”
我是新来的。有人能帮我怎么做吗。你在找这个吗:
db.col.updateOne(
{ name: "xyz" },
{ "$set": { 'answer.$[i].test': null } },
{ arrayFilters: [{ "i.type": { $ne: "C" } }] }
)
结果:
{
"name" : "xyz",
"answer" : [
{
"type" : "C",
"from" : 0.0
},
{
"type" : "M",
"from" : 0.0,
"test" : null
},
{
"type" : "P",
"from" : 0.0,
"test" : null
}
]
}
如果要更新集合中的所有文档,请使用updateMany()
并跳过筛选{name:“xyz”}
当然,您可以像这样手动运行更新:
db.col.find().forEach(function (doc) {
doc.answer.forEach(function (i) {
if (i.type != "C")
i.test = null;
})
db.col.updateOne(
{ _id: doc._id },
{ $set: doc }
)
})
但是你必须承认,arrayFilters
更短更方便