Node.js Basics — MongoDB Upserts and Queries
Tags: node, webdev, programming, javascript
Published: 2021-01-24 01:17:56

**Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62**

**Subscribe to my email list now at http://jauyeung.net/subscribe/**

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.