更新包含在 MongoDB 文档中的数组中的子文档 [英] Update a subdocument contained in an array contained in a MongoDB document

查看:27
本文介绍了更新包含在 MongoDB 文档中的数组中的子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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'.通过该查询,我可以在主文档中添加一个架构文档.子文档存储在一个数组中:

The above query is a Meteor collection, and 'Documents.update' maps to 'db.documents.update' in MongoDB documentation (http://docs.mongodb.org/manual/applications/update/). With that query I can add a schema document inside the main document. Subdocuments are stored in an array:

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

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

I want to modify the name and size attributes of the subdocuments with this query:

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

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

But that operation append a new object directly under schema and deletes the array:

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

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

How can I modify the query to change the attributes avoiding this issue? After the query I would like to have this document:

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

推荐答案

您可以使用使用 $ 位置运算符,用于标识选择器中匹配的数组元素,如下所示:

You can update an existing array element using a $set operation that uses the $ positional operator to identify the array element matched in the selector like this:

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 对象中的元素.

This will replace the matched schema element with the one included in the $set object.

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

If you only want to update individual fields of the targeted schema element, you can use dot notation. For example, to only update the size and name fields:

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

这篇关于更新包含在 MongoDB 文档中的数组中的子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆