gpt4 book ai didi

javascript - 如何在不知道其位置的情况下删除 Mongo 对象(向下嵌套 2 个数组)?

转载 作者:可可西里 更新时间:2023-11-01 09:57:27 25 4
gpt4 key购买 nike

我需要删除嵌套在下面文档中的“答案”对象之一。我有我正在寻找的答案的文本。我没有问题的索引或我需要深入到数组中的答案。

例如,我知道我要深入研究的问题的文本是“这是一个问题”。我要删除的答案是“答案一”。

你会怎么做?

这是示例 MongoDB 文档:(测验有问题;有问题有答案)

{
name: "Sample Quiz",
categories: [
{ name: "testcategory1", description: "this is a test category" }
,{ name: "categoryTWO", description: "the second category" }
],

questions: [

{ text: "This is a question."
,answers: [
{text: "Answer One", affected_categories: "testcategory1"}
,{text: "Answer Two", affected_categories: "testcategory1"}
,{text: "Answer Three", affected_categories: "categoryTWO"}
]
}

,{ text: "This is the second question."
,answers: [
{text: "Mepho One", affected_categories: "testcategory1"}
,{text: "Answer Toodlydoo", affected_categories: "testcategory1"}
,{text: "Lehmen Sumtin", affected_categories: "categoryTWO"}
]
}
],
}

当我删除嵌套在下一层的项目时(在本例中,是一个问题),我可以使用如下查询来完成:

    Quizzes.update(
{ _id: quizID, 'questions.text': questionText },
{ $pull: { questions: {text: questionText }}}
);

(如此处所述:http://docs.mongodb.org/manual/core/update/#Updating-ModifierOperations,在标题为“更新元素而不指定其位置”的部分中)

我尝试将其扩展为:

Quizzes.update(
{ _id: quizID, 'answers.text': answerText },
{ $pull: { questions: {text: questionText {answers: {text: answerText }}}}}
);

但没有任何运气。

任何想法将不胜感激。

最佳答案

使用 positional operator结合 $pull 条件:

> db.quizzes.update(
{_id:<quizID>, "questions.text":"This is the second question."},
{$pull:{ "questions.$.answers":{"text":"Answer Toodlydoo"}}}
);

以上内容用于从第二个问题中删除第二个答案。

关于javascript - 如何在不知道其位置的情况下删除 Mongo 对象(向下嵌套 2 个数组)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16799455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com