如何在一个查询中多次更新而不共享给简单查询? [英] How to update in one query, multiple times without sharing to simple queries?
问题描述
我有以下模型:
{
"_id": "unique1",
"companyBases": [
{
"_id": "company base 1",
"vehicles": [
....some objects
]
},
{
"_id": "company base 2",
"vehicles": [
....some objects
]
},
{
"_id": "company base 3",
"vehicles": [
....some objects
]
}
]
}
我想通过覆盖某些匹配的"companyBases"中的"vehicles"数组来更新此文档.这是我的输入:
I would like to update this document by overwritting "vehicles" array in some "companyBases" that matches. This is my input:
[
{
"_id": "company base 1",
"vehicles": [
array thats overwrites old array "vehicles", where _id of object in "companyBases" is equeal to "company base 1"
....some new objects
]
},
{
"_id": "company base 3",
"vehicles": [
array thats overwrites old array "vehicles", where _id of object in "companyBases" is equeal to "company base 2"
....some new objects
]
}
]
我想通过使用一个查询而不是多个简单查询来多次更新-使用$ set更新(如果可能的话),因为这可能会影响性能,每次更新200-300次一个请求.
I would like to update multiple times by using one query, not multiple simple queries - update with $set (if it's possible), because it could impact on performance with update 200-300 times per one request.
预期输出(在模型中):
Expected output (in model):
{
"_id": "unique1",
"companyBases": [
{
"_id": "company base 1",
"vehicles": [
....some new objects
]
},
{
"_id": "company base 2",
"vehicles": [
....some objects
]
},
{
"_id": "company base 3",
"vehicles": [
....some new objects
]
}
]
}
推荐答案
我们可以准备多个数组过滤器在同一查询中.数组过滤器标识与该过滤器匹配的数组元素. 以下是一个示例:
We can prepare multiple array filters in the same query. An array filter identifies the array elements which match that filter. The following is an example:
db.collection.update(
{"_id":"unique1"},
{
$set:{
"companyBases.$[filter1].vehicles":[
{
"tag":"new1"
}
],
"companyBases.$[filter2].vehicles":[
{
"tag":"new2"
}
]
}
},
{
"arrayFilters":[
{
"filter1._id":"company base 1"
},
{
"filter2._id":"company base 3"
}
]
}
)
数据集:
{
"_id": "unique1",
"companyBases": [
{
"_id": "company base 1",
"vehicles": [
{
"tag":"old"
}
]
},
{
"_id": "company base 2",
"vehicles": [
{
"tag":"old"
}
]
},
{
"_id": "company base 3",
"vehicles": [
{
"tag":"old"
}
]
}
]
}
输出:
{
"_id" : "unique1",
"companyBases" : [
{
"_id" : "company base 1",
"vehicles" : [
{
"tag" : "new1"
}
]
},
{
"_id" : "company base 2",
"vehicles" : [
{
"tag" : "old"
}
]
},
{
"_id" : "company base 3",
"vehicles" : [
{
"tag" : "new2"
}
]
}
]
}
这篇关于如何在一个查询中多次更新而不共享给简单查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!