我正在使用Node.js和MongoDB開發恢復數據庫Web應用程序。我正在嘗試更新位於多維數組內的單個記錄。假如每個數組都有自己的對象ID,如何更新career_development字段中的單個數組?MongoDB:使用其對象ID更新多維數組
{
"_id": ObjectId("57f35a25983d521a90518efd"),
"email": "[email protected]",
"first_name": "John",
"last_name": "Doe",
"created_at": ISODate("2016-10-04T07:28:37.407Z"),
"career_development": [
{
"_id": ObjectId("5811aefcb7880316e4497406"),
"company_name": "TestCompanyName 1",
"company_location": "Texas, United States"
},
{
"_id": ObjectId("5811afb7b7880316e4497407"),
"company_name": "TestCompanyName 2",
"company_location": "South Carolina, United States"
},
{
"_id": ObjectId("5811afbfb7880316e4497408"),
"company_name": "TestCompanyName 3",
"company_location": "Florida, United States"
}
]
}
使用['$' (https://docs.mongodb.com/v3.2/reference/operator/update/positional/)[點符號]文件/#文檔d ot-notation)as db.collection.update({「career_development._id」:ObjectId(「5811aefcb7880316e4497406」)},{「$ set」:{「career_development。$。company_name」:「TestCompanyName 1 Updated」}}) ' – chridam
@chridam謝謝,這工作。但如果說career_development是動態的呢?我怎麼能這樣做: var dynamic_variable = posting_data.type; {「$ set」:{dynamic_variable +「。$。company_name」:「TestCompanyName 1 Updated」}} ?? – Carl
沒問題。您可以使用括號表示創建更新對象,如 'var dynamic_variable = posting_data.type; var query = {}; var updateObj = {「$ set」:{}}; query [dynamic_variable +「._ id」] = ObjectId(「5811aefcb7880316e4497406」); updateObj [「$ set」] [dynamic_variable +「。$。company_name」] =「TestCompanyName 1 Updated」; db.collection.update(query,updateObj)' – chridam