Chad Johnson
Chad Johnson

Reputation: 21905

Why does this MongoDB aggregate query return nothing?

I have the following aggregate query:

db.radars.aggregate([
    {
        $group: {
            _id: '$locationId',
            count: {$sum: 1}
        },
    },
    {
        $match: {
            loggedAt: {
                $gte: new Date('2014-01-01T00:00:00Z'),
                $lte: new Date('2016-12-31T00:00:00Z')
            }
        }
    }
]);

I definitely have data matching the criteria:

enter image description here

But I get nothing:

enter image description here

Does anyone know why this might be happening?

Upvotes: 2

Views: 3738

Answers (2)

David
David

Reputation: 1141

If some of your aggregation queries return a result, but some return no result, then you need to fix your query (other answers address this).

But if none of your aggregation queries return a result, you may not be connected to the right database.

Connect to a database using a connection string

Check your connection string. Note databasename in the following:

MONGODB_URI=mongodb+srv://username:[email protected]/databasename

Connect to a database using Mongoose connection options object

How to connect to a specific database ...

Connect to a database using MongoDB shell

show dbs; to list the databases

use mydatabase; to connect to a database

If you aren't sure which one you should be using, after connecting to a database you can run

show collections in MongoDB shell to see if it contains your data.

Listing databases and collections using NodeJS:

List databases with NodeJS)

List collections with NodeJS

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 312115

After the $group, the pipeline will contain docs with just the fields defined in the $group: _id and count so there's no loggedAt field to match against.

So, depending on the output you're looking for, reorder your pipeline to do the $match first or add an accumulator for loggedAt to your $group so its still available.

For example:

db.radars.aggregate([
    {
        $group: {
            _id: '$locationId',
            count: {$sum: 1},
            loggedAt: {$push: '$loggedAt'}
        },
    },
    {
        $match: {
            loggedAt: { $elemMatch: {
                $gte: new Date('2014-01-01T00:00:00Z'),
                $lte: new Date('2016-12-31T00:00:00Z')
            } }
        }
    }
]);

Upvotes: 5

Related Questions