gpt4 book ai didi

javascript - MongoDB Node.JS 驱动程序 : create, 使用数组追加和更新文档

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:43 25 4
gpt4 key购买 nike

我希望使用 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
    }
    ]
    }

    最佳答案

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

    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,驱动程序将自动为您创建一个。

    此代码基于我的博客系列中的代码。一些对您有用的链接:

    该代码利用了 $push 和 $each 的组合。请参阅https://docs.mongodb.com/manual/reference/operator/update/push/#example-push-each了解更多详细信息。

    该代码还利用了位置 $ 运算符。请参阅https://docs.mongodb.com/manual/reference/operator/update/positional/了解更多详细信息。

    关于javascript - MongoDB Node.JS 驱动程序 : create, 使用数组追加和更新文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59879070/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com