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

查看:92
本文介绍了更新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"}

推荐答案

您可以使用$set操作(使用

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天全站免登陆