2015-04-17 110 views
0
db.employee.insert(
{ 
_id: 'shop1', 
ShopName: 'Londis', 
ShopAddress: 'Clea boy', 
Owner: 'Tim Byrne', 
ShopContactNumber: '0877733121', 
Employee: [ 
      { 
      EmployId: '1', 
      EmployName: 'Pat Power', 
      EmployContactNumber: 0876395224, 
      EmployAddress: 'Lacka Rd', 
      Salary: 500.00, 
      Hours: 40, 
      PayType: 'Cheque', 
      Wage: 9.00, 
      EmployeeType: 'Manager' 
      }, 
      { 
      EmployId: '2', 
      EmployName: 'Craig Coad', 
      EmployContactNumber: 0873347582, 
      EmployAddress: 'Portlaw', 
      Salary: 400.00, 
      Hours: 32, 
      PayType: 'Bank', 
      Wage: 8.65, 
      EmployeeType: 'FloorStaff' 
      }, 
      { 
      EmployId: '3', 
      EmployName: 'Joe Bloggs', 
      EmployContactNumber: 0861234567, 
      EmployAddress: 'Waterford', 
      Salary: 510.00, 
      Hours: 12, 
      PayType: 'Cheque', 
      Wage: 9.50, 
      EmployeeType: 'Manager' 
      }]}); 

我想更新某個特定員工的項目狀態。 例如,我會想更新第1項設置EmployName =「帕特里克·力」EmployeId =「1」,因爲該員工存在:Mongodb更新嵌入字段

db.students.update(
    {'_id':'shop1','Employee.EmployId':'1'}, 
    {$set:{'Employee.$.EmployName':'Patrick Power'} } 
); 

這是我一直在努力做但它不起作用?

我在做什麼錯了?

+1

可能重複[?我如何更新基於查詢的子dcoument陣列的子文檔字段(http://stackoverflow.com/questions/29667369/how-can-i-update-the-sub-document-field-from-the-sub-dcoument-array-based-on-the) – Yogesh

回答

1

這可能對您有所幫助:

db.collectionName.update({ 
"_id": "shop1", 
'Employee': { 
    '$elemMatch': { 
     'EmployId': '1' 
    } 
} 
}, { 
$set: { 
    'Employee.$.EmployName': 'Patrick Power' 
} 
}); 
+0

非常感謝。工作:) –