Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To fill a property field in an array of objects using the Mongoose aggregate pipeline, you can use the $addFields stage followed by the $map and $mergeObjects operators. Here's an example:

db.collection.aggregate([
  {
    $addFields: {
      "arrayOfObjects": {
        $map: {
          input: "$arrayOfObjects",
          as: "obj",
          in: {
            $mergeObjects: [
              "$$obj",
              { "propertyToFill": "value" }
            ]
          }
        }
      }
    }
  }
]);

In this example, arrayOfObjects is the field containing the array of objects that you want to update. The $addFields stage creates a new field called arrayOfObjects with the updated objects.

The $map operator goes through each object in the array and returns a new object with the updated property. The $$obj variable represents each object in the array, and the $mergeObjects operator merges the existing object with a new object that contains the property you want to fill.

Finally, the $addFields stage adds the newly updated arrayOfObjects field to the output documents.

Note that you can replace "value" with a variable or another field value if you need to fill the property dynamically.