summaryrefslogtreecommitdiff
path: root/jstests/aggregation/sources/addFields/use_cases.js
blob: 21479f6eef036118e782069f8abb1ba957a6fd18 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
 * $addFields can be used to add fixed and computed fields to documents while preserving the
 * original document. Verify that using $addFields and adding computed fields in a $project yield
 * the same result.
 */

(function() {
"use strict";

// For arrayEq.
load("jstests/aggregation/extras/utils.js");

const collName = jsTest.name();
const coll = db.getCollection(collName);
coll.drop();

const nDocs = 10;
for (let i = 0; i < nDocs; i++) {
    assert.commandWorked(coll.insert({"_id": i, "2i": i * 2, "3i": i * 3}));
}

// Add the minimum, maximum, and average temperatures, and make sure that doing the same
// with addFields yields the correct answer.
// First compute with $project, since we know all the fields in this document.
let projectPipe = [{
    $project: {
        "2i": 1,
        "3i": 1,
        "6i^2": {"$multiply": ["$2i", "$3i"]},
        // _id is implicitly included.
    }
}];
let correct = coll.aggregate(projectPipe).toArray();

// Then compute the same results using $addFields.
let addFieldsPipe = [{
    $addFields: {
        "6i^2": {"$multiply": ["$2i", "$3i"]},
        // All other fields are implicitly included.
    }
}];
let addFieldsResult = coll.aggregate(addFieldsPipe).toArray();

// Then assert they are the same.
assert(arrayEq(addFieldsResult, correct),
       "$addFields does not work the same as a $project with computed and included fields");

// $addFields with an empty spec is allowed and should be treated as a no-op
let addFieldsEmptySpecPipe = [{$addFields: {}}];

assert(arrayEq(coll.aggregate(addFieldsEmptySpecPipe).toArray(), coll.aggregate().toArray()),
       "$addFields with empty spec did not result in no-op");
})();