Caspian D
Caspian D

Reputation: 11

MongoDB Node.JS driver: create, append, and update documents with arrays

I am looking to achieve the following operations with the MongoDB Node.JS driver, could this be performed with an optimal approach? There are three possible operations required: create, append, and update.

  1. Create the following document.
{
    "_id": "hello_world_cluster",
        "items": [
            {
                "item_name": "my_item_one",
                "first_seen": 1000,
                "last_seen": 1000,
                "logic": true
            }
        ]
}
  1. Append new items to an array.
{
    "_id": "hello_world_cluster",
        "items": [
            {
                "item_name": "my_item_one",
                "first_seen": 1000,
                "last_seen": 1000,
                "logic": true
            },
            {
                "item_name": "my_item_two",
                "first_seen": 2000,
                "last_seen": 2000,
                "logic": true
            },
            {
                "item_name": "my_item_three",
                "first_seen": 3000,
                "last_seen": 3000,
                "logic": true
            }
        ]
}
  1. Update items that are found in an array.
{
    "_id": "hello_world_cluster",
        "items": [
            {
                "item_name": "my_item_one",
                "first_seen": 1000,
                "last_seen": 4000,
                "logic": false
            },
            {
                "item_name": "my_item_two",
                "first_seen": 2000,
                "last_seen": 2000,
                "logic": true
            },
            {
                "item_name": "my_item_three",
                "first_seen": 3000,
                "last_seen": 3000,
                "logic": true
            }
        ]
}

Upvotes: 1

Views: 672

Answers (1)

Lauren Schaefer
Lauren Schaefer

Reputation: 706

I drafted some sample code for you:

const { MongoClient } = require('mongodb');

async function main() {
    /**
     * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
     */
    const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";

    /**
     * The Mongo Client you will use to interact with your database
     */
    const client = new MongoClient(uri, { useUnifiedTopology: true });

    try {
        // Connect to the MongoDB cluster
        await client.connect();

        // Make the appropriate DB calls

        // Create a new document
        await createDocument(client);

        // Append new items to the items array
        await appendNewItemsToArray(client);

        // Update items in the items array
        await updateItemsInArray(client);


    } finally {
        // Close the connection to the MongoDB cluster
        await client.close();
    }
}

main().catch(console.error);

async function createDocument(client) {
    const result = await client.db("NameOfYourDb").collection("NameOfYourCollection").insertOne({
        "_id": "UniqueId1",
        "items": [
            {
                "item_name": "my_item_one",
                "first_seen": 1000,
                "last_seen": 1000,
                "logic": true
            }
        ]
    });
    console.log(`New document created with the following id: ${result.insertedId}`);
}

async function appendNewItemsToArray(client) {
    const result = await client.db("NameOfYourDb").collection("NameOfYourCollection").updateOne(
        { "_id": "UniqueId1" },
        {
            $push: {
                items: {
                    $each: [
                        {
                            "item_name": "my_item_two",
                            "first_seen": 2000,
                            "last_seen": 2000,
                            "logic": true
                        },
                        {
                            "item_name": "my_item_three",
                            "first_seen": 3000,
                            "last_seen": 3000,
                            "logic": true
                        }]
                }
            }
        });

    console.log(`${result.matchedCount} document(s) matched the query criteria.`);
    console.log(`${result.modifiedCount} document(s) was/were updated.`);
}

async function updateItemsInArray(client) {
    const result = await client.db("NameOfYourDb").collection("NameOfYourCollection").updateOne(
        { "_id": "UniqueId1", "items.item_name": "my_item_one" },
        { $set: { "items.$.logic": false, "items.$.last_seen": 4000 } }
    );

    console.log(`${result.matchedCount} document(s) matched the query criteria.`);
    console.log(`${result.modifiedCount} document(s) was/were updated.`);
}

One important thing to note: The _id needs to be unique for every document within a collection. You do not have to manually create the _id. If you omit _id from the document, the driver will automatically create one for you.

This code is based on code from my blog series. Some helpful links for you:

The code takes advantage of combining $push and $each. See https://docs.mongodb.com/manual/reference/operator/update/push/#example-push-each for more details on that.

The code also takes advantage of the positional $ operator. See https://docs.mongodb.com/manual/reference/operator/update/positional/ for more details on that.

Upvotes: 1

Related Questions