0% found this document useful (0 votes)
11 views5 pages

$add Fields

$addFields is an aggregation stage in MongoDB that adds new fields to documents while retaining existing ones, functioning similarly to $project. It allows for various operations such as adding multiple fields, modifying nested documents, overwriting existing fields, and removing fields using the $$REMOVE variable. The aggregation framework is designed to transform data without altering the original documents in the collection.

Uploaded by

myfamilypics35
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views5 pages

$add Fields

$addFields is an aggregation stage in MongoDB that adds new fields to documents while retaining existing ones, functioning similarly to $project. It allows for various operations such as adding multiple fields, modifying nested documents, overwriting existing fields, and removing fields using the $$REMOVE variable. The aggregation framework is designed to transform data without altering the original documents in the collection.

Uploaded by

myfamilypics35
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

$addFields (aggregation)

$addFields
Adds new fields to documents. $addFields outputs documents that contain all
existing fields from the input documents and newly added fields.
The $addFields stage is equivalent to a $project stage that explicitly specifies all
existing fields in the input documents and adds the new fields.
Note
You can also use the $set stage, which is an alias for $addFields.
We can do the following operations on $addFields
1. Add new Fields
2. Add new fields 2/multiple stages
3. Adding Fields in nested documents
4. Overwrite Existing documents
5. Replace one filed with another Field
6. Add element to the array
7. Remove fields.

The aggregation framework in MongoDB is designed to transform and


return data without modifying the source documents.It doesn't update
the underlying documents in your collection.

1.Add new Fields


Here, $ sum takes array of values.

2. Add new fields 2/multiple stages

3. Adding Fields to an Embedded Document


4. Overwriting an existing field
Before After
5. Replace one field with another.

6.Add Element to arrays


You can use $addFields with a $concatArrays expression to add an element to an existing
array field.

$ConcatArray takes array of values

Syntax: $concatArray : [“Fieldname”,[data1,data2………]]

7.Remove fields
You can use $addFields with the $$REMOVE variable to remove document fields.
After Before

Note:
$sum
$concatArrays
$$REMOVE

You might also like