将新项目添加到嵌套数组,并根据插入的项目更新现有元素
{
"_id": {
"$oid": "6200c86d083ef16be6dae5b1"
},
"type": "Hair_Length",
"values": [
{
"name": "Bald / Clean Shaven",
"value": "bald",
"default": "yes"
},
{
"name": "Crew Cut",
"value": "crewcut"
},
{
"name": "Short",
"value": "Short"
},
{
"name": "Medium",
"value": "Medium"
},
{
"name": "Long",
"value": "Long"
},
{
"name": "Chin Length",
"value": "ChinLength"
},
{
"name": "Shoulder Length",
"value": "ShoulderLength"
},
{
"name": "Dreadlocks",
"value": "Dreadlocks"
}
]
}
大家好!如果我将名称和值作为JSON对象获得,则只有我将获得“默认值”:“是”,除了名称和值之外,我们还需要更新和删除,如果我希望我还需要更新和删除你很感激
它的伙计们
{
"_id": {
"$oid": "6200c86d083ef16be6dae5b1"
},
"type": "Hair_Length",
"values": [
{
"name": "Bald / Clean Shaven",
"value": "bald",
"default": "yes"
},
{
"name": "Crew Cut",
"value": "crewcut"
},
{
"name": "Short",
"value": "Short"
},
{
"name": "Medium",
"value": "Medium"
},
{
"name": "Long",
"value": "Long"
},
{
"name": "Chin Length",
"value": "ChinLength"
},
{
"name": "Shoulder Length",
"value": "ShoulderLength"
},
{
"name": "Dreadlocks",
"value": "Dreadlocks"
}
]
}
Good day guys! if I get name and value as json object then only I will update or add to this doc if incase we get "default":"yes" in addition to name and value then we need to update and delete if default is already exist I hope you got point
appreciate it guys tq
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您知道您的新项目是否是默认项目,因此在查询之前,最好在执行该问题之前将查询调整为相关情况。但是,仅出于挑战的目的,这是一个只有一个查询的解决方案。我建议您将其分解为两个查询,并在每种情况下仅使用一个查询。
您可以在另一种情况。
主要想法是有两种主要情况:新项目是默认的。在这两种情况下,您首先要从列表中滤出具有值的元素,如果它们在那里,则与新项目匹配。然后,如果默认新项目,则从列表中的项目中删除默认字段。直到现在,我们才能将新项目插入列表。
询问:
首先,您使用
$ addfields
和$ filter
如果存在,则使用$ facet 。其中之一是新项目默认情况下的情况,而在e上则没有。然后,您选择使用
$ cond
的使用方法,然后使用$ setunion
添加新项目。最后一步是$ MERGE
将新文档替换为旧文档。Since you know if your new item is a default item or not, before the query, it is better to adjust the query to the relevant case before executing it. But just for the sake of the challenge, this is a solution with one query only. I advise you to break it into two queries and use only one at each case.
You can see it work on the playground on one case and on another case.
The main idea is that there are two main cases: the new item is default or not. On both cases you start by filtering out from the list the element with value matches the new item if they are there. Then, if the new item is default you remove the default field from the items in the list. Only now we can insert the new item to the list.
Query:
First you add your new item using
$addFields
and$filter
out the item if exists, then you create the documents for the two cases using$facet
. one of them to the case where the new item is default, and on e for the case it is not. then you choose which one to use, using$cond
, and add the new item to it using$setUnion
. Last step is$merge
to replace the new doc with the old one.