我有一个嵌套的mongo数组
{
"_id": 1,
"date": "2024-09-30",
"employees": [
{
"_id": 101,
"name": "John Doe",
"company": "ABC Corp",
"department": "HR",
"salary": 50000,
"contactNumber": "123-456-7890"
},
{
"_id": 102,
"name": "A",
"company": "XYZ Corp",
"department": "HR",
"salary": 500100,
"contactNumber": "1333-456-7890"
},
{
"_id": 103,
"name": "B",
"company": "XYZ Corp",
"department": "HR",
"salary": 500100,
"contactNumber": "1333-456-7890"
}
]
}
我需要更新101的工资并添加新会员104。我该怎么做一次更新?
我可以进行 2 次更新。一种是使用 ArrayFilters 更新 101 的工资,另一种是 $push 104 到数组。以下是询问,
db.collection.updateOne(
{ _id: 1 }, // Match the document with _id: 1
{
$set: { "employees.$[emp].salary": 60000 } // Set the new salary for employee with _id: 101
},
{
arrayFilters: [ { "emp._id": 101 } ] // Array filter to target the specific employee with _id: 101
}
)
db.collection.updateOne(
{ _id: 1 }, // Match the document with _id: 1
{
$push: {
employees: {
_id: 104,
name: "New Employee",
company: "New Corp",
department: "HR",
salary: 70000,
contactNumber: "987-654-3210"
}
}
}
)
有什么方法可以在同一查询中添加新员工并更新现有员工。?
我想我可以使用聚合来做到这一点。但在性能方面哪个更好?