我想编写一个查询来更新单个查询中的多个文档,请建议我可行的方法。
以下是我的mongo文档。
[
{
"_id" : ObjectId("5b0f0a2ca1f6633032c204cd"),
"parent_id" : ObjectId("5b0f09e1a1f6633032c204cc"),
"name" : "ABC",
"userType": "admin"
},
{
"_id" : ObjectId("5b0f0a2ca1f6633032c204ce"),
"parent_id" : ObjectId("5b0f09e1a1f6633032c204cc"),
"name" : "DEF",
"userType": "admin"
},
{
"_id" : ObjectId("5b0f0a2ca1f6633032c204cf"),
"parent_id" : ObjectId("5b0f09e1a1f6633032c204cc"),
"name" : "GHI",
"userType": "admin"
},
{
"_id" : ObjectId("5b0f0a2ca1f6633032c204d0"),
"parent_id" : ObjectId("5b0f09e1a1f6633032c204cc"),
"name" : "XYZ",
"userType": "admin"
}
]
我一直在跟踪代码中更新的对象,如何通过查询在数据库中更新该对象。
[
{
"_id" : ObjectId("5b0f0a2ca1f6633032c204cd"),
"parent_id" : ObjectId("5b0f09e1a1f6633032c204cc"),
"name" : "ABC123",
"color":"red"
"userType": "admin"
},
{
"_id" : ObjectId("5b0f0a2ca1f6633032c204ce"),
"parent_id" : ObjectId("5b0f09e1a1f6633032c204cc"),
"name" : "DEF123",
"color":"blue"
"userType": "admin"
},
{
"_id" : ObjectId("5b0f0a2ca1f6633032c204cf"),
"parent_id" : ObjectId("5b0f09e1a1f6633032c204cc"),
"name" : "GHI123",
"color":"green"
"userType": "admin"
},
{
"_id" : ObjectId("5b0f0a2ca1f6633032c204d0"),
"parent_id" : ObjectId("5b0f09e1a1f6633032c204cc"),
"name" : "XYZ123",
"color":"rgb(14,256,12, 1)"
"userType": "admin"
}
]
请给我建议正确的方法,否则我们可以做到吗?
答案 0 :(得分:4)
您基本上需要在mongodb中进行bulkWrite
操作
const array = [
{
"_id" : ObjectId("5b0f0a2ca1f6633032c204cd"),
"parent_id" : ObjectId("5b0f09e1a1f6633032c204cc"),
"name" : "ABC123",
"color":"red"
"userType": "admin"
},
{
"_id" : ObjectId("5b0f0a2ca1f6633032c204ce"),
"parent_id" : ObjectId("5b0f09e1a1f6633032c204cc"),
"name" : "DEF123",
"color":"blue"
"userType": "admin"
},
{
"_id" : ObjectId("5b0f0a2ca1f6633032c204cf"),
"parent_id" : ObjectId("5b0f09e1a1f6633032c204cc"),
"name" : "GHI123",
"color":"green"
"userType": "admin"
},
{
"_id" : ObjectId("5b0f0a2ca1f6633032c204d0"),
"parent_id" : ObjectId("5b0f09e1a1f6633032c204cc"),
"name" : "XYZ123",
"color":"rgb(14,256,12, 1)"
"userType": "admin"
}
]
最后的查询
Model.bulkWrite(
array.map((data) =>
({
updateOne: {
filter: { _id: data._id },
update: { $set: data }
}
})
)
})