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.

Categories
MongoDB Node.js Basics

Node.js Basics — Deleting and Updating MongoDB Documents

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.

Delete a Document

We can delete a document within our MongoDB collection.

To do that, 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)
    const deleteResult = await testCollection.deleteOne({ name: { $type: "string" } });
    console.log(deleteResult)
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We pass in a query into the deleteOne method to delete all the entries with the name that has type string.

Also, we can delete all the entries with the name set to type string with the deleteMany method:

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)
    const deleteResult = await testCollection.deleteMany({ name: { $type: "string" } });
    console.log(deleteResult)
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

Change a Document

We can update a document with thw updateOne method.

For example, we can write:

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

const filter = { foo: 'bar' };
const updateDocument = {
  $set: {
    foo: 'baz',
  },
};

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

We call the updateOne method to find the item with the query object in the first argument.

The 2nd argument is the document to update the item with.

The $set property indicates that we want to add or update the key-value pair in the object we set as its value.

Update Arrays in a Document

We can update arrays in a document by accessing its property.

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 updateDocument = {
      $set: { "items.0.toppings": "veggie" }
    };
    const updateResult = await testCollection.updateOne(query, updateDocument);
    console.log(updateResult)
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We call insertOne to add the entry we want into our collection.

Then we define the updateDocument object with the $set property to set the item we want.

items.0.toppings will get the toppings property of the first entry ofitems array and update it.

To match all array elements, we can use the $[] positional operator:

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 updateDocument = {
      $set: { "items.$[].toppings": "veggie" }
    };
    const updateResult = await testCollection.updateOne(query, updateDocument);
    console.log(updateResult)
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

Now both items in the items array has 'veggie' appended into it.

Conclusion

We can delete a document and update an array in an existing document with the MongoDB driver.

Categories
Node.js Basics

Node.js Basics — Level DB

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.

Level DB

Most apps need to store data somewhere.

They most likely use a database to store their data.

One way to store data within a Node app is to use the Level DB database.

It’s a key-value pair database, which makes it a NoSQL database.

It supports JSON right off the bat so we won’t have to do much to get and set the data.

The database is stored in a file.

To use Level DB, we run:

npm install level

to install the package.

Then we can use it by writing:

const level = require('level')
const db = level('my-db')
db.put('name', 'level',  (err) => {
  if (err) {
    return console.log(err)
  }
  db.get('name',  (err, value) => {
    if (err) {
      return console.log(err)
    }
    console.log(`name=${value}`)
  })
})

We get the database file by calling the level function with the database file’s path.

Then we call db.put with the key and value as the first 2 arguments to save the key-value pair.

The 3rd argument is a function to get the error from the err parameter in case there is any.

The db.get method lets us get a piece of data by the key.

The first argument is the key .

The 2nd argument is the callback in the same format.

Then we should see the output:

name=level

displayed.

We can also store a bunch of key-value pairs with one operation.

For instance, we can write:

const level = require('level')
const db = level('my-db')

const ops = [
  { type: 'del', key: 'father' },
  { type: 'put', key: 'name', value: 'james smith' },
  { type: 'put', key: 'dob', value: '1990-01-01' },
  { type: 'put', key: 'spouse', value: 'jane smith' },
  { type: 'put', key: 'occupation', value: 'waiter' }
]

db.batch(ops, function (err) {
  if (err){
     return console.log(err)
  }
  console.log('Great success')
})

We have an ops array with a bunch of objects to define the operations.

The type is the type of the operation we want to do. They are the same as the method names.

The key is needed for getting the items to delete.

And the value is what we insert as the value of the key.

We can also chain the del and put methods to manipulate the key-value pairs:

const level = require('level')
const db = level('my-db')

db.batch()
  .del('father')
  .put('name', 'james smith')
  .put('dob', '1990-01-01')
  .put('spouse', 'jane smith')
  .put('occupation', 'waiter')
  .write(function () { console.log('Done!') })

We can read our data with a read stream.

For example, we can write:

const level = require('level')
const db = level('my-db')

db.put('foo', 'bar', function(error) {
  if (error){
    return console.log(error)
  }
  const stream = db.createReadStream();
  stream
    .on('data', function({ key, value }) {
      console.log(`${key}=${value}`);
    })
    .on('error', function(error) {
      console.log(error);
    })
    .on('end', function() {
      console.log('end');
    });
});

We call db.createReadStream to create the read stream.

Then we listen to the data to get the key-value pairs from the key and value properties respectively.

Conclusion

We can use the Level DB database to store key-value pairs in our app.