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.

Categories
MongoDB Node.js Basics

Node.js Basics — MongoDB Basics

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.

MongoDB

MongoDB is another NoSQL database that we can use in our Node.js app.

It can also store key-value pairs.

MongoDB is hosted in a server either through the cloud or in our own servers.

To use it in our Node app, we run:

npm install mongodb

Then we can use it in our package.

We also need to install the MongoDB server from https://www.mongodb.com/try/download/community

Once we installed the package in our project and the server, we can connect to it in our app.

To do that, we write:

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

async function run() {
  try {
    await client.connect();
    await client.db("test").command({ ping: 1 });
    console.log("Connected successfully to server");
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We call MongoClient function with the connection string to connect to the database server with the given connection string.

In the run function, we call client.connect() to do the connection.

Then we call client.db to connect to the given database.

The command method sends the command we want to the server.

The client.close method closes the connection and clean up any resources.

Inserting Data

We can get the collection we want to save our data to and save the data there.

To do that, we 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({ foo: 'bar' });
    console.log(result)
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We connect to the database we want with the db method.

Then we get the collection we want to save data to with the collection method.

Next, we call insertOne on the resolved collection object to insert an object.

And finally, we log the result.

Also, we can use the insertMany method to insert multiple documents.

For example, we can write:

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

const pizzaDocuments = [
  { name: "Sicilian pizza", shape: "square" },
  { name: "New York pizza", shape: "round" },
  { name: "Grandma pizza", shape: "square" },
];

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany(pizzaDocuments);
    console.log(result)
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We just pass in an array into the insertMany method.

Conclusion

We can use the MongoDB driver to connect to a MongoDB database and then insert one or more documents into our database collection.