Драйвер MongoDB Node.JS: создание, добавление и обновление документов с массивами - PullRequest
2 голосов
/ 23 января 2020

Я хочу выполнить следующие операции с драйвером MongoDB Node.JS. Может ли это быть выполнено оптимальным способом? Требуются три возможных операции: создать, добавить и обновить.

  1. Создать следующий документ.
{
    "_id": "hello_world_cluster",
        "items": [
            {
                "item_name": "my_item_one",
                "first_seen": 1000,
                "last_seen": 1000,
                "logic": true
            }
        ]
}
Добавление новых элементов в массив.
{
    "_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
            }
        ]
}
Обновить элементы, найденные в массиве.
{
    "_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
            }
        ]
}

1 Ответ

2 голосов
/ 23 января 2020

Я составил пример кода для вас:

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.`);
}

Одна важная вещь, на которую следует обратить внимание: _id должен быть уникальным для каждого документа в коллекции. Вам не нужно вручную создавать _id. Если вы опустите _id в документе, драйвер автоматически создаст его для вас.

Этот код основан на коде из моей серии блогов. Некоторые полезные ссылки для вас:

Код использует комбинацию $ pu sh и $ каждый. Подробнее см. https://docs.mongodb.com/manual/reference/operator/update/push/#example -pu sh -each .

Код также использует позиционный оператор $. Подробнее см. https://docs.mongodb.com/manual/reference/operator/update/positional/.

...