gpt4 book ai didi

mongodb - 更新包含在 MongoDB 文档中的数组中的子文档

转载 作者:IT老高 更新时间:2023-10-28 13:18:00 25 4
gpt4 key购买 nike

Documents.update(
{_id: Session.get("current_document_id")},
{$push: {schema: {type: "text", size: size, name: name, label: label}}}
);

上面的查询是一个 Meteor 集合,'Documents.update' 映射到 MongoDB 文档 (http://docs.mongodb.org/manual/applications/update/) 中的 'db.documents.update'。通过该查询,我可以在主文档中添加架构文档。子文档存储在一个数组中:

Document:
schema:
array:
{type: "text", size: 6, name: "first_name", label: "First name"},
{type: "text", size: 6, name: "last_name", label: "Last name"}

我想用这个查询修改子文档的名称和大小属性:

Documents.update(
{_id: Session.get("current_document_id"), 'schema' : "first_name"},
{$push: {schema: {type: "text", size: 7, name: name, label: "First Name2"}}}
);

但该操作直接在模式下附加一个新对象并删除数组:

Document:
schema:
{type: "text", size: 7, name: "first_name", label: "First Name2"}

如何修改查询以更改属性以避免此问题?查询后我想要这个文件:

Document:
schema:
array:
{type: "text", size: 7, name: "first_name", label: "First name2"},
{type: "text", size: 6, name: "last_name", label: "Last name"}

最佳答案

您可以使用 $set 操作更新现有数组元素,该操作使用 $位置运算符来识别选择器中匹配的数组元素,如下所示:

Documents.update(
{_id: Session.get("current_document_id"), 'schema.name': "first_name"},
{$set: {'schema.$': {type: "text", size: 7, name: name, label: "First Name2"}}}
);

这会将匹配的 schema 元素替换为 $set 对象中包含的元素。

如果您只想更新目标 schema 元素的各个字段,则可以使用点表示法。例如,仅更新 sizename 字段:

Documents.update(
{_id: Session.get("current_document_id"), 'schema.name': "first_name"},
{$set: {'schema.$.size': 7, 'schema.$.name': name}}
);

关于mongodb - 更新包含在 MongoDB 文档中的数组中的子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13777097/

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