MongoDB Node.JS驱动程序:使用数组创建,附加和更新文档 [英] MongoDB Node.JS driver: create, append, and update documents with arrays
问题描述
我希望通过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.
- 创建以下文档。
{
"_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
}
]
}
推荐答案
我为您起草了一些示例代码:
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:
- https://www.mongodb.com/blog/post/quick-start-nodejs-mongodb--如何连接到您的数据库
- https://www.mongodb.com/blog/post/quick-start-nodejs-- mongodb--如何创建文档
- https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-update-documents
- https://www.mongodb.com/blog/post/quick-start-nodejs-mongodb--how-to-get-connected-to-your-database
- https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-create-documents
- https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-update-documents
该代码利用了$ push和$ each的组合优势。参见 https://docs.mongodb.com/手动/参考/操作符/更新/推送/#example-push-each 以获得更多详细信息。
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.
该代码还利用了位置$操作员。参见 https://docs.mongodb.com/manual/reference/operator/更新/位置/ 以获取更多详细信息。
The code also takes advantage of the positional $ operator. See https://docs.mongodb.com/manual/reference/operator/update/positional/ for more details on that.
这篇关于MongoDB Node.JS驱动程序:使用数组创建,附加和更新文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!