Console.logging out my aggregation pipeline for test

Hi there,

I am new to MongoDB and I wanted to make sure I have executed my code correctly to display an aggregation pipeline for testing purposes.

I am trying to console.log the below which does not return anything back to me. Is this an issue with the testing sample data?

const { MongoClient, ServerApiVersion } = require(‘mongodb’);
const uri = “mongodb+srv://michaelhardie:Finalfusion63@cluster0.semgmfx.mongodb.net/?retryWrites=true&w=majority”;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
client.connect(async err => {
const collection = client.db(“sample_airbnb”).collection(“listingsAndReviews”);
// perform actions on the collection object

const pipeline = [
    {
      '$match': {
        'accommodates': {
          '$gt': 4
        }, 
        'price': {
          '$lt': 500
        }, 
        'amenities': 'Hair dryer'
      }
    }, {
      '$sort': {
        'price': 1
      }
    }, {
      '$project': {
        'name': 1, 
        'amenities': 1, 
        'price': 1, 
        'image': 1, 
        'descriptions': 1
      }
    }, {
      '$limit': 20
    }
  ]

  const agg = await collection.aggregate(pipeline).toArray();

  console.log(agg)

client.close();
});

Thanks in advance,
Michael

1 Like

When no document comes out from a pipeline, any of the following could be wrong.

  1. You have the wrong database
  2. You have the wrong collection
  3. You have the wrong query, $match in this case

I would proceed in the following way.

  1. Remove the $match stage and see if I have any document. If you have no document, then is is problem 1. or 2. Check both names. Note that the name can be correct but you might be on the wrong cluster.

  2. Add back each of $match clauses one by one verify if you have documents or not.

  3. When you have no documents, you know that the culprit is the last clause added.

3a. Check if the field name is correct? Names are case sensitives.
3b. Check if the value checked has the same type as the fiekd values

1 Like

I have checked you query directly on Atlas, and your query seems fine giving 730 total (no limit) documents in return.

I haven’t tried other parts in a Node.js environment but here I suspect two things: serverApi: ServerApiVersion.v1 and .toArray(). They might not be working to your expectation.

open a node REPL in your project folder (so you can access installed libraries in it). try without setting serverapiversion and then try to print the result of aggregation directly.

I have now tested your whole code.

The problem is in one of your username, password, or cluster address. wait about 30 seconds and check your log to see “Uncaught MongoError: Topology is closed, please connect”

I have tried this on my cluster, the only differences are those 3, and your code works fine.

Thanks you for getting back to me so quickly.

I am glad the code is executing. Although on my end I am still unable to log out anything successfully (no error messages either)

there is a possibility your driver is not installed correctly. but first, try connecting to your cluster with mongo shell or Compass to see if your URI is fine.

URI is fine. I was able to connect via mongo shell

michaelhardie@<comp_details> mongoDB % node --version
v16.15.1
michaelhardie@<comp_details> mongoDB % npm --version
8.11.0
michaelhardie@<comp_details> mongoDB % node index.js
michaelhardie@<comp_details> mongoDB %

now then, create a new folder and

  • npm init -y # start a temp project
  • npm install mongodb # install mongodb driver
  • node # start REPL
  • copy-paste and run your code, and see/share what happens.

if this gives you a result, we may say the installation is broken in the other project.

This is what been returned

const { MongoClient, ServerApiVersion } = require(‘mongodb’);
undefined
const uri = “mongodb+srv://michaelhardie:thepassword@cluster0.semgmfx.mongodb.net/?retryWrites=true&w=majority”;
undefined
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
undefined
client.connect(async err => {
… // perform actions on the collection object

… const collection = client.db(“sample_airbnb”).collection(“listingsAndReviews”);

… const pipeline = [
… {
… ‘$match’: {
… ‘accommodates’: {
… ‘$gt’: 4
… },
… ‘price’: {
… ‘$lt’: 500
… },
… ‘amenities’: ‘Hair dryer’
… }
… }, {
… ‘$sort’: {
… ‘price’: 1
… }
… }, {
… ‘$project’: {
… ‘name’: 1,
… ‘amenities’: 1,
… ‘price’: 1,
… ‘image’: 1,
… ‘descriptions’: 1
… }
… }, {
… ‘$limit’: 20
… }
… ]

… const agg = await collection.aggregate(pipeline).toArray();

… console.log(agg);

… client.close();
… });

I have node.js v18.0.0 and npm v8.6.0. mongodb v4.9.1 gets installed, and your code run perfectly to return a result in a few seconds.

maybe nodejs installation has a problem, or your firewall happened to disallow node to use the network.

or maybe you forgot to import the sample database in that cluster which results in zero response because no document returns. this type of forgetfulness can happen anytime, so go check that too.

otherwise, my ideas are depleted.

I manage to get “Uncaught ReferenceError: client is not defined” error message. Unsure what this is referring to. But regardless thank you for assisting

a new idea to test if your installs have a problem:

  • go to https://github.com/Schniz/fnm go to and download this very lightweight node version manager. it is easy to install/uninstall; single executable, a single folder, and easy commands to start. plus this makes it kinda portable manager; eval "$(fnm env)" when you need these versions of node.
  • set a new node version, start a repl, try above fresh project to test your code. since the node’s executable will be on a different folder path, freshly installed, and should not be broken if no network errors, then your code should work fine too. if not the culprit is your OS or PC.