我正在使用Node.js和MongoDB开发一个简历数据库Web应用程序。我试图更新位于多维数组内的单个记录。我如何从career_development字段更新单个数组下面给定的每个数组都有自己的对象ID?
{
"_id": ObjectId("57f35a25983d521a90518efd"),
"email": "john.doe@gmail.com",
"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"
}
]
}
使用$
位置运算符,点符号为
db.collection.update(
{ "career_development._id": ObjectId("5811aefcb7880316e4497406") },
{
"$set": {
"career_development.$.company_name": "TestCompanyName 1 Updated"
}
}
);
如果career_development
是动态的,那么您可以使用括号符号创建一个更新对象:
var dynamic_variable = posted_data.type,
query = {},
updateObj = { "$set": { } };
query[dynamic_variable +"._id"] = ObjectId("5811aefcb7880316e4497406");
updateObj["$set"][dynamic_variable +".$.company_name"] = "TestCompanyName 1 Updated";
db.collection.update(query, updateObj)
你是说数组看起来像这样吗?如果不是这样,我们可以使用elemMatch来获取文档,遍历它并更新它。让我知道,我会把问题贴在这里。
"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"
}
],
[
{
"_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"
}
]