Update the subdocument contained in the array contained in the MongoDB document

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

The above query is a collection of Meteor, and "Documents.update" to "db.documents.update" in the MongoDB documentation (http://docs.mongodb.org/manual/applications/update/). With this 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 change the name and size attributes of the attached documents 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 this operation adds a new object directly according to the scheme and deletes the array:

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

How to modify a query to change attributes avoiding this problem? Upon request, 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"} 
+7
source share
1 answer

You can update an existing array element using the $set operation, which uses the $ positioning operator to identify the array element matched in the selector, as follows:

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

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

If you want to update the individual fields of the target schema element, you can use dot notation. For example, to 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}} ); 
+19
source

All Articles