Skip to content

Commit 62e2ff6

Browse files
authored
Merge pull request #5740 from AyushG3112/addFields-aggregate-feature
Add $addFields pipeline operator via a Mongoose Function
2 parents 06f39e8 + cc41aa2 commit 62e2ff6

File tree

3 files changed

+65
-17
lines changed

3 files changed

+65
-17
lines changed

lib/aggregate.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,41 @@ Aggregate.prototype.append = function() {
106106
return this;
107107
};
108108

109+
/**
110+
* Appends a new $addFields operator to this aggregate pipeline.
111+
* Requires MongoDB v3.4+ to work
112+
*
113+
* ####Examples:
114+
*
115+
* // adding new fields based on existing fields
116+
* aggregate.addFields({
117+
* newField: '$b.nested'
118+
* , plusTen: { $add: ['$val', 10]}
119+
* , sub: {
120+
* name: '$a'
121+
* }
122+
* })
123+
*
124+
* // etc
125+
* aggregate.addFields({ salary_k: { $divide: [ "$salary", 1000 ] } });
126+
*
127+
* @param {Object} arg field specification
128+
* @see $addFields https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/
129+
* @return {Aggregate}
130+
* @api public
131+
*/
132+
Aggregate.prototype.addFields = function(arg) {
133+
var fields = {};
134+
if (typeof arg === 'object' && !util.isArray(arg)) {
135+
Object.keys(arg).forEach(function(field) {
136+
fields[field] = arg[field];
137+
});
138+
} else {
139+
throw new Error('Invalid addFields() argument. Must be an object');
140+
}
141+
return this.append({$addFields: fields});
142+
};
143+
109144
/**
110145
* Appends a new $project operator to this aggregate pipeline.
111146
*

package-lock.json

Lines changed: 17 additions & 17 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

test/aggregate.test.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,19 @@ describe('aggregate: ', function() {
444444
});
445445
});
446446

447+
describe('addFields', function() {
448+
it('(object)', function(done) {
449+
var aggregate = new Aggregate();
450+
451+
assert.equal(aggregate.addFields({ a: 1, b: 1, c: 0 }), aggregate);
452+
assert.deepEqual(aggregate._pipeline, [{ $addFields: { a: 1, b: 1, c: 0 } }]);
453+
454+
aggregate.addFields({ d: {$add: ['$a','$b']} });
455+
assert.deepEqual(aggregate._pipeline, [{ $addFields: { a: 1, b: 1, c: 0 } }, { $addFields: { d: {$add: ['$a','$b']} } }]);
456+
done();
457+
});
458+
});
459+
447460
describe('facet', function() {
448461
it('works', function(done) {
449462
var aggregate = new Aggregate();

0 commit comments

Comments
 (0)