MongoDB Node.JS驱动程序:使用数组创建,附加和更新文档 [英] MongoDB Node.JS driver: create, append, and update documents with arrays

查看:94
本文介绍了MongoDB Node.JS驱动程序:使用数组创建,附加和更新文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望通过MongoDB Node.JS驱动程序实现以下操作,这可以通过最佳方法来执行吗?需要进行三种可能的操作:创建,附加和更新。

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. 创建以下文档。



{
    "_id": "hello_world_cluster",
        "items": [
            {
                "item_name": "my_item_one",
                "first_seen": 1000,
                "last_seen": 1000,
                "logic": true
            }
        ]
}




  1. 附加新项目



{
    "_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. 更新在数组中找到的项目。



{
    "_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
            }
        ]
}


推荐答案

我为您起草了一些示例代码:

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

需要注意的一件事:_id对于集合中的每个文档都必须是唯一的。您不必手动创建_id。如果您在文档中省略_id,驱动程序将自动为您创建一个。

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:

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆