<p>我不太清楚问题到底是什么。简而言之:是的,您必须更新“parent”对象,是的,您可以使用<code>$set</code>或替换整个文档,这将是默认行为。区别主要是锁、并发和所有权问题,这有点复杂。以下是您的一些顾虑的详细信息:</p>
<blockquote>
<p>Updating a nested mongodb collection using a cursor</p>
</blockquote>
<p>请注意,没有“嵌套集合”,只有嵌入的文档。这很重要,因为mongodb中的第一类公民总是实际的文档本身。例如,<code>find()</code>将返回文档,而不是仅返回嵌入文档的子集。你可以做预测,但这只是一个输出转换,可以说。在</p>
<blockquote>
<p>I can do a find() on the collection for the course. I get a cursor for that. </p>
</blockquote>
<p>您得到了一个游标,但是由于您查询的是主键,因此只能有一个匹配项(主键是唯一的),也就是说,您可以使用<code>findOne()</code>,并且不需要迭代单个结果。在</p>
<blockquote>
<p>E.g. Each document contains an array of students for each class.</p>
</blockquote>
<p>这些通常应该是学生的参考资料,也就是说,应该有一个单独的学生集合,因为你不想因为学生暂时没有被分配到任何课程而失去学生。在</p>
<blockquote>
<p>The pymongo documentation site does not talk about the set option in the update function. Unless I use that I believe mongodb updates the whole document.</p>
</blockquote>
<p>这是真的。您可以对文档的<code>students</code>数组执行<code>$set</code>。这样可以避免重写任何其他字段,例如<code>class</code>。另一方面,如果在您编辑学生时其他人更改了<code>class</code>,那么这些更新是否仍然有意义?所有权不明确是我对嵌入文档的主要顾虑。在</p>
<blockquote>
<p>Also calling update with a query option by passing in the _id seems unnecessary because I just did the query and have a handle to the record</p>
</blockquote>
<p>…但究竟什么是记录的句柄?句柄是一个不可变的、唯一的、通常很短的标识符。就像id一样,<code>_id</code><em>是句柄。我不懂python,但我想您可以编写一个方法,它获取指向数据库对象的指针并执行更新,因为知道每个数据库对象都必须有一个名为<code>_id</code>的字段。但是从数据库的角度来看,代码中的指针不是句柄,而是id。在</p>