我有一个如下用户文档:
{
"userId": "249869823570",
"name": "john",
"country": "usa",
"active": true,
"serviceProviders": [
{
"serviceProvidersId": "897892893",
"serviceProvidersName": "AT&T",
"active": true,
"serviceProviderContactPerson": []
},
{
"serviceProvidersId": "82589628569",
"serviceProvidersName": "T-Mobile",
"active": true,
"serviceProviderContactPerson": []
}
]
}
,我想创建3种方法来插入/更新/删除serviceProviderContactPerson。我的困境是,我的主文档中有一组serviceProviders,而serviceProvider中有一个serviceProviderContactPerson列表...在mongo中,最佳实践是什么?
serviceProviderContactPerson文档将如下所示:
{
"contactId": "873498798",
"name": "Mark",
"email": "mark@tmobile.com",
"phone": "917-475-4637"
}
答案 0 :(得分:0)
您可以使用update执行3.6中的所有操作。
插入一个新的数组元素,其中serviceProvidersId =“ 897892893”
db.colname.update(
{"serviceProviders.serviceProvidersId":"897892893"},
{$push: {"serviceProviders.$.serviceProviderContactPerson":serviceProviderContactPersonDoc}}
)
更新电话,其中serviceProvidersId =“ 897892893”和contactId =“ 873498798”
db.colname.update(
{},
{$set: {"serviceProviders.$[sp].serviceProviderContactPerson.$[spc].phone":phone value}},
{arrayFilters:[{"sp.serviceProvidersId":"897892893"}, {"spc.contactId":"873498798"}]}
)
删除数组元素,其中serviceProvidersId =“ 897892893”和contactId =“ 873498798”
db.colname.update(
{},
{$pull: {"serviceProviders.$[sp].serviceProviderContactPerson":{"contactId":"873498798"}}},
{arrayFilters:[{"sp.serviceProvidersId":"897892893"}]}
)