我对arrayList中的特定文档有要求,其示例JSON字符串为
{ “_id”:ObjectId(“58b9339502be203f6b476664”), “_docType”:“测试”, “type”:“mongoUpdate”,
"createdDateTime" : "2017-03-03 09:12:53.080",
"contacts" : [
{
"firstName" : "FirstName",
"lastName" : "LastName",
"email" : "someName@email.com",
"contactType" : "Business.",
"phoneNumber" : "1234567890",
"createdDateTime" : "2017-03-03 09:13:04.229",
"lastModifiedDTM" : "2017-03-03 09:13:04.229",
},
{
"firstName" : "FirstName2",
"lastName" : "LastName2",
"email" : "someName@email.com2",
"contactType" : "Business2.",
"phoneNumber" : "1234567890",
"createdDateTime" : "2017-03-03 09:13:04.229",
"lastModifiedDTM" : "2017-03-03 09:13:04.229",
},
{
"firstName" : "FirstName3",
"lastName" : "LastName3",
"email" : "someName@email.com3",
"contactType" : "Business.3",
"phoneNumber" : "12345678903",
"createdDateTime" : "2017-03-03 09:13:04.229",
"lastModifiedDTM" : "2017-03-03 09:13:04.229",
}
]
}
说我必须在上面的json中更新其中一个。 我已经使用$ set操作来更新上面的数组,当我看到mongo db中的内容时,我看到整个数组被单次出现的联系替换。
我使用的更新命令是
{$设置:{ “接触”:[{ “名字”: “test0103)12”, “姓氏”: “test0103”, “电子邮件”: “test0103”, “contactType”: “test0103”,“phoneNumber的“:” test0103" , “createdDateTime”: “test0103”}]}}
执行此操作后,我看到3的整个数组列表被替换为单个联系人实例。
最后我输出为 “联系方式”:[ {
"firstName" : "test0103)12",
"lastName" : "test0103",
"email" : "test0103",
"contactType" : "test0103",
"phoneNumber" : "test0103",
"createdDateTime" : "test0103"
}]
答案 0 :(得分:0)
以下是示例代码
首先使用_id查找文档。这里我收集的是用户
` User.findOne({'_id': 58b9339502be203f6b476664},(err,res) => {
if(res.contacts.length > 0){
var contacts = res.contacts;
var contactsList = [];
var contactobject = {};
// suppose you want to update the contact with firstname - FirstName2
contacts.map((contact,key)=>{
if(contact.firstName == "firstName2"{
contactobject.firstName = "Your updated name";
contactobject.lastName = "Your updated name";
// similary all values you want to update
// Then push to an array after updating new data
contactsList.push(contactObject);
}
else {
// if not the required contact to update
// simply push
contactsList.push(contact);
}
})
//在地图功能之后,现在更新新的联系人
User.update({email:email},
{$set:{contacts: contactsList}},(err,result) => {
User.findOne({'_id':res._id}).then(updateuser => {
resolve(updateuser);
})
})
}
})`
试试这个,它有效