Subsequent MongoDB aggregate() calls operate on the result of the previous call!? (using NodeJS driver)

0

Issue

Consider the following code:

const db = mongodb.getDb();
            
// Results count
let count = (await db.collection('sec').aggregate(aggregateQuery)
    .group({ _id: null, count: { $sum: 1 } })
    .project({ _id: 0, count: 1 })
    .toArray());
console.dir(count)

// test
let test = await db.collection('sec').aggregate(aggregateQuery).toArray();
console.dir(test)

The aggregate(aggregateQuery) filters the collection ad performs a lookup with another collection.
The first query counts all documents resulting from the aggregate, and it outputs [ { count: 2086 } ] as expected.
In my mind, test should contain a bunch of documents filtered from the collection (according to the aggregate operations), but it is just [ { count: 2086 } ], as in the first query!

If in the second query instead of aggregate(aggregateQuery) I put find(), it outputs all the collection’s documents, as expected, so I guess there is something I am missing in the aggregate() function…

Solution

The object passed as a parameter inside aggregate (aggregateQuery in this case) is modified by the following functions (group and project), so when it is used again in the second aggregate call, it is different and yields different results.

Answered By – Mattia Brozzo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More