mongodb 中的更新查询不起作用

Update query in mongodb not working

我有一个存储员工详细信息的文档。这是我的文档结构。

{
    "emp_id" : 1,
    "Employee_Name" : "Fareed Khan Jan",
    "Employee_Contact" : "07492897789",
    "Employee_Gender" : "Male",
    "Employee_Address" : "Lewisham",
    "IS_Available" : "YES",
    "Employee_Reports" : [ 
        {
     "Report_Title" : "Initial Project Design",
     "Report_Details" : "This is a sample report.",
     "Date_Submit" : "26/10/2015"
        }
    ],
    "Employee_Salary" : [ 
        {
            "month_year" : "Jan-2015",
            "actual_salary" : 200.0000000000000000,
            "bonus" : 0.0000000000000000,
            "penalty" : 0.0000000000000000,
            "bonus_pen_detail" : "NA",
            "total_amount_paid" : 200.0000000000000000
        }, 
        {
            "month_year" : "Feb-2015",
            "actual_salary" : 200.0000000000000000,
            "bonus" : 0.0000000000000000,
            "penalty" : 0.0000000000000000,
            "bonus_pen_detail" : "NA",
            "total_amount_paid" : 200.0000000000000000
        }
    ]
}

现在我想更新嵌入文档 'Employee_Salary',其中 "month-year" 是 'Feb-2015'。我编写了以下查询,但它删除了 'Employee_Salary' 中的所有数据并更新了其中的一个。我不想删除里面的其他数据。

db.employees.update
(
      { 'emp_id': 1, 'Employee_Salary.month_year' : "Feb-2015" }, 
      { '$set': { 
        'Employee_Salary': [
            {
            "month_year" : "Feb-2015",
            "actual_salary" : 200.0000000000000000,
            "bonus" : 80.0000000000000000,
            "penalty" : 0.0000000000000000,
            "bonus_pen_detail" : "NA",
            "total_amount_paid" : 280.0000000000000000 
            }
            ]
    }}
)

这是因为你用新数组告诉它 $set Employee_Salary。

要修改您在查找中查找的那个,您必须使用 $ 运算符:

{ '$set': { 
        "Employee_Salary.$.bonus" : "80.0000000000000000"
}}