Categories
MongoDB Node.js Basics

Node.js Basics — MongoDB Cursor

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Event API

We can get query results from our collection with Node.js’s Event API.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5,
        qty: 100
      },
      {
        name: "KFC",
        rating: 4,
        qty: 121
      },
    ]);
    console.log(result)
    const query = {
      name: "Popeye",
    };
    const cursor = testCollection.find(query);
    cursor.on("data", data => console.log(data));
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

to watch for the 'data' event so that we can get the data from the result.

Fetch Results as an Array

We can ferch results as an array.

For instane, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5,
        qty: 100
      },
      {
        name: "KFC",
        rating: 4,
        qty: 121
      },
    ]);
    console.log(result)
    const query = {
      name: "Popeye",
    };
    const cursor = testCollection.find(query);
    const allValues = await cursor.toArray();
    console.log(allValues);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We call the toArray method on the cursor which returns a promise that resolves to the result from test collection.

Cursor Utility Methods

The cursor object has a few utility methods.

The count method returns the number of results retrieved from a collection.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5,
        qty: 100
      },
      {
        name: "KFC",
        rating: 4,
        qty: 121
      },
    ]);
    console.log(result)
    const query = {
      name: "Popeye",
    };
    const cursor = testCollection.find(query);
    const count = await cursor.count();
    console.log(count);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

to get the items returned from the query.

The rewind method lets us reset the cursor to its initial position in the set of returned documents.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5,
        qty: 100
      },
      {
        name: "KFC",
        rating: 4,
        qty: 121
      },
    ]);
    console.log(result)
    const query = {
      name: "Popeye",
    };
    const cursor = testCollection.find(query);
    const firstResult = await cursor.toArray();
    console.log("First count: ", firstResult.length);
    await cursor.rewind();
    const secondResult = await cursor.toArray();
    console.log("Second count: ", secondResult.length);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We called rewind and get the result from the cursor before and after calling rewind .

We get the same result in each console log because we called rewind to reset the cursor.

Conclusion

We can listen to the data event and get the data from there.

Also, we can use the cursor to do various retrieval operations.

Categories
MongoDB Node.js Basics

Node.js Basics — MongoDB Query and Cursor

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Retrieve Data

We can retrieve data by using methods that comes with the MongoDB driver.

The simplest way to get items from a collection is to use the find method.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5,
        qty: 100
      },
      {
        name: "KFC",
        rating: 4,
        qty: 121
      },
    ]);
    console.log(result)
    const query = {
      name: "Popeye",
      qty: {
        $gte: 90,
        $lt: 110,
      },
    };
    const cursor = testCollection.find(query);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We make a query with the qty property to find the documents wirh the qty property greater than or equal to 90 and less than 110.

To find the first document in a collection that meets the condition given in a query, we can use the findOne method with the same argument.

The cursor has the forEach method to let us traverse the query results.

Aggregate

To make a query with a given criteria and then group them together, we can use the $match and $group properties together in a query.

For instance, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5,
        qty: 100
      },
      {
        name: "KFC",
        rating: 4,
        qty: 121
      },
    ]);
    console.log(result)
    const query = [
      {
        $match: {
          qty: {
            $gte: 90,
            $lt: 110,
          },
        },
      },
      {
        $group: {
          _id: "$status",
          count: {
            $sum: 1,
          },
        },
      },
    ];
    const cursor = testCollection.aggregate(query);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

In the code above, we get all the entries with the qty property that’s greater than or equal to 90 and less than 110.

Then we group all the items by counting the entries with the $sum operator.

Now we should get the count of the number of items that are found with the query.

Access Data From a Cursor

We can access data from a cursor in different ways.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5,
        qty: 100
      },
      {
        name: "KFC",
        rating: 4,
        qty: 121
      },
    ]);
    console.log(result)
    const query = {
      name: "Popeye",
      qty: {
        $gte: 90,
        $lt: 110,
      },
    };
    const cursor = testCollection.find(query);
    await cursor.forEach(doc => console.log(doc));
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

query has the query that we want to make.

Then we call forEach on the cursor to loop through each entry.

Conclusion

With the MongoDB Node.js client, there are several ways we can use to retrieve the data we want.

Categories
MongoDB Node.js Basics

Node.js Basics — MongoDB Upserts and Queries

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Upserts

We can do upserts by setting the upsert option to true .

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertOne({
      name: "Popeye",
    });
    console.log(result)
    const query = { name: "Popeye" };
    const update = {
      $set: { name: "Popeye", address: "3 Nassau St" }
    };
    const options = { upsert: true };
    const updateResult = await testCollection.updateOne(query, update, options);
    console.log(updateResult)
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We set the upsert property in the options object to true so that we can insert the entry when it’s not available.

The $set property lets us set the properties we want to set.

Querying Data

We can query data in to search for in the collection and then do our updates to the results.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertOne({
      name: "Popeye",
    });
    console.log(result)
    const query = { name: "Popeye" };
    const cursor = testCollection.find(query);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

to make a query to find the documents with the name set to 'Popeye' .

We call the find method to find all the entries with that value.

And then we call the forEach method to search for items.

We can also search for the items with a given quantity.

To do that, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5
      },
      {
        name: "KFC",
        rating: 4
      },
    ]);
    console.log(result)
    const query = {
      rating: { $eq: 5 }
    };
    const cursor = testCollection.find(query);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We inserted 2 entries into our collection.

Then we make the query with the find method.

The $eq key means we want to search for the items that equals something.

Therefore, we search for any documents with the rating property equal to 5.

This is the same as:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5
      },
      {
        name: "KFC",
        rating: 4
      },
    ]);
    console.log(result)
    const query = {
      rating: 5
    };
    const cursor = testCollection.find(query);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

Conclusion

We can query items by using various operations supported by MongoDB.

Categories
MongoDB Node.js Basics

Node.js Basics — MongoDB Complex Updates and Upserts

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Filtered Positional Operator for Arrays in Documents

We can get the position and insert what we want into it.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertOne({
      name: "Popeye",
      address: "1 Sweethaven",
      items: [
        {
          type: "pizza",
          size: "large",
          toppings: ["garlic, spinach"],
        },
        {
          type: "calzone",
          toppings: ["ham"],
        },
      ],
    });
    console.log(result)
    const query = { name: "Popeye" };
    const options = {
      arrayFilters: [{
        "orderItem.type": "pizza",
        "orderItem.size": "large",
      }]
    };
    const updateDocument = {
      $push: { "items.$[orderItem].toppings": "veggie" }
    };
    const updateResult = await testCollection.updateOne(query, updateDocument, options);
    console.log(updateResult)
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We add the items into the toppings array of the object with the given type and size in the items array.

The items.$[orderItem].toppings gets the item with the given result from the arrayFilters search.

It’ll search the items array for the entry by replacing orderItem with the index of the search result in arrayFilters .

Now we should see veggie as the 2nd wntr of the toppings array property.

The document should now be:

{
   "_id":{
      "$oid":"5f68f03c9b873d2818970b52"
   },
   "name":"Popeye",
   "address":"1 Sweethaven",
   "items":[
      {
         "type":"pizza",
         "size":"large",
         "toppings":[
            "garlic, spinach",
            "veggie"
         ]
      },
      {
         "type":"calzone",
         "toppings":[
            "ham"
         ]
      }
   ]
}

Upsert

We can upsert one or more documents with the updateOne , replaceOne or updateMany methods.

To update a single entry, we can use the updateOne method:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertOne({
      name: "Popeye",
    });
    console.log(result)
    const query = { name: "Popeye" };
    const update = { $set: { name: "Popeye", address: "3 Nassau St" } };
    const options = {};
    const updateResult = await testCollection.updateOne(query, update, options);
    console.log(updateResult)
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We insert an item with a name key.

Then we call the updateOne with the query object to find the item with the given name value.

Then we create the update object with the $set property to update the properties with the items.

The replaceOne method lets us replace an item with another one.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertOne({
      name: "Popeye",
    });
    console.log(result)
    const query = { name: "Popeye" };
    const update = { name: "Popeye", address: "3 Nassau St" };
    const options = {};
    const updateResult = await testCollection.replaceOne(query, update, options);
    console.log(updateResult)
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We call replaceOne to replace the item with name set to 'Popeye' to an object with both the name and address properties.

Conclusion

We can call various methods to update our MongoDB documents.

Categories
MongoDB Node.js Basics

Node.js Basics — MongoDB Comparison Operators

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Comparison Operators

We can use comparison operators to query for items with one or more quantities bigger than or less than some quantity.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5
      },
      {
        name: "KFC",
        rating: 4
      },
    ]);
    console.log(result)
    const query = { rating: { $gt: 4 } };
    const cursor = testCollection.find(query);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

The $gt key means greater than, so we search for the documents that have rating bigger than 4.

Logical Operators

We can also add the $not key to negate some query.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5
      },
      {
        name: "KFC",
        rating: 4
      },
    ]);
    console.log(result)
    const query = { rating: { $not: { $gt: 4 } } };
    const cursor = testCollection.find(query);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We find all the documents that has rating not greater than 4.

This means we find the items with rating less than or equal to 4.

We can query for more than one property in a query.

For instance, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5,
        qty: 100
      },
      {
        name: "KFC",
        rating: 4,
        qty: 120
      },
    ]);
    console.log(result)
    const query = {
      rating: { $eq: 5 },
      qty: { $gt: 90 }
    };
    const cursor = testCollection.find(query);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

With this query, we search for any document with rating equal to 5 and qty larger than 90.

Evaluation Operators

There are evaluation operators we can use to do more queries.

The $mod operator lets us find the items with a quantity that has a given remainder.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5,
        qty: 100
      },
      {
        name: "KFC",
        rating: 4,
        qty: 121
      },
    ]);
    console.log(result)
    const query = {
      qty: { $mod: [10, 0] }
    };
    const cursor = testCollection.find(query);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We make the query with the $mod operator. The first entry of the array is the number we divide by.

And the 2nd entry is the remainder we’re looking for after we divide by the first number.

Therefore, we should get the first entry returned.

Conclusion

We can use various comparison operators to make queries for documents with MongoDB.