{"id":2475,"date":"2025-03-07T23:19:04","date_gmt":"2025-03-07T15:19:04","guid":{"rendered":"https:\/\/www.laixuexila.com\/?p=2475"},"modified":"2025-03-09T13:11:08","modified_gmt":"2025-03-09T05:11:08","slug":"node-js-%e8%bf%9e%e6%8e%a5-mongodb","status":"publish","type":"post","link":"https:\/\/www.laixuexila.com\/index.php\/2025\/03\/07\/node-js-%e8%bf%9e%e6%8e%a5-mongodb\/","title":{"rendered":"Node.js \u8fde\u63a5 MongoDB"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">\u8981\u5728 Node.js \u4e2d\u8fde\u63a5\u548c\u64cd\u4f5c MongoDB\uff0c\u4f60\u9700\u8981\u4f7f\u7528\u5b98\u65b9\u7684 MongoDB Node.js \u9a71\u52a8\u7a0b\u5e8f\u3002\u4ee5\u4e0b\u662f\u5982\u4f55\u5728 Node.js \u4e2d\u8fde\u63a5\u5230 MongoDB \u6570\u636e\u5e93\u7684\u6b65\u9aa4\u3002<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>1. \u5b89\u88c5 MongoDB Node.js \u9a71\u52a8<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">\u9996\u5148\uff0c\u4f60\u9700\u8981\u901a\u8fc7 npm \u5b89\u88c5 MongoDB \u7684 Node.js \u9a71\u52a8\u7a0b\u5e8f\u3002\u6253\u5f00\u7ec8\u7aef\u5e76\u8fdb\u5165\u4f60\u7684\u9879\u76ee\u76ee\u5f55\uff0c\u7136\u540e\u8fd0\u884c\u4ee5\u4e0b\u547d\u4ee4\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm install mongodb<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">\u8be5\u547d\u4ee4\u4f1a\u5b89\u88c5\u5b98\u65b9\u7684 MongoDB Node.js \u9a71\u52a8\u3002<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>2. \u8fde\u63a5\u5230 MongoDB<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">\u5b89\u88c5\u5b8c\u9a71\u52a8\u7a0b\u5e8f\u540e\uff0c\u4f60\u53ef\u4ee5\u4f7f\u7528\u5b83\u6765\u8fde\u63a5 MongoDB \u6570\u636e\u5e93\u3002\u4ee5\u4e0b\u662f\u4e00\u4e2a\u7b80\u5355\u7684\u8fde\u63a5\u793a\u4f8b\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const { MongoClient } = require('mongodb');\n\n\/\/ MongoDB \u8fde\u63a5\u5b57\u7b26\u4e32\uff0c\u5047\u8bbe MongoDB \u5728\u672c\u5730\u8fd0\u884c\nconst url = 'mongodb:\/\/localhost:27017';\nconst dbName = 'test';  \/\/ \u8981\u8fde\u63a5\u7684\u6570\u636e\u5e93\u540d\u79f0\n\nasync function connectToMongoDB() {\n  const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });\n\n  try {\n    \/\/ \u8fde\u63a5\u5230 MongoDB \u670d\u52a1\u5668\n    await client.connect();\n    console.log('Connected to MongoDB');\n\n    \/\/ \u9009\u62e9\u6570\u636e\u5e93\n    const db = client.db(dbName);\n\n    \/\/ \u4f7f\u7528\u6570\u636e\u5e93\u8fdb\u884c\u64cd\u4f5c\uff0c\u4f8b\u5982\u9009\u62e9\u96c6\u5408\n    const collection = db.collection('users');\n\n    \/\/ \u793a\u4f8b\uff1a\u67e5\u8be2\u6240\u6709\u6587\u6863\n    const users = await collection.find().toArray();\n    console.log(users);\n  } catch (err) {\n    console.error('MongoDB connection error:', err);\n  } finally {\n    \/\/ \u786e\u4fdd\u8fde\u63a5\u5728\u5b8c\u6210\u65f6\u5173\u95ed\n    await client.close();\n  }\n}\n\nconnectToMongoDB();<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>\u4ee3\u7801\u8bf4\u660e\uff1a<\/strong><\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>MongoClient<\/strong>\uff1a\u7528\u4e8e\u8fde\u63a5\u5230 MongoDB \u7684\u5ba2\u6237\u7aef\u3002<\/li>\n\n\n\n<li><strong>useNewUrlParser<\/strong> \u548c <strong>useUnifiedTopology<\/strong>\uff1a\u8fd9\u4e24\u4e2a\u9009\u9879\u662f\u9a71\u52a8\u7a0b\u5e8f\u7684\u914d\u7f6e\u9879\uff0c\u7528\u4e8e\u786e\u4fdd\u5728\u8fde\u63a5\u65f6\u4f7f\u7528\u65b0\u7684\u89e3\u6790\u5668\u548c\u62d3\u6251\u7ba1\u7406\u5668\u3002<\/li>\n\n\n\n<li><strong>client.connect()<\/strong>\uff1a\u5f02\u6b65\u8fde\u63a5\u5230 MongoDB \u6570\u636e\u5e93\u3002<\/li>\n\n\n\n<li><strong>db.collection(&#8216;users&#8217;)<\/strong>\uff1a\u9009\u62e9\u540d\u4e3a <code>users<\/code> \u7684\u96c6\u5408\u3002<\/li>\n\n\n\n<li><strong>find().toArray()<\/strong>\uff1a\u67e5\u8be2\u96c6\u5408\u4e2d\u7684\u6240\u6709\u6587\u6863\u5e76\u8f6c\u6362\u4e3a\u6570\u7ec4\u3002<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>3. \u6267\u884c CRUD \u64cd\u4f5c<\/strong><\/h3>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>\u63d2\u5165\u6570\u636e<\/strong><\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>async function insertData() {\n  const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });\n\n  try {\n    await client.connect();\n    const db = client.db(dbName);\n    const collection = db.collection('users');\n\n    \/\/ \u63d2\u5165\u4e00\u6761\u6570\u636e\n    const result = await collection.insertOne({ name: 'Alice', age: 25, city: 'New York' });\n    console.log(`New document inserted with _id: ${result.insertedId}`);\n  } catch (err) {\n    console.error('Insert operation failed:', err);\n  } finally {\n    await client.close();\n  }\n}\n\ninsertData();<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>\u67e5\u8be2\u6570\u636e<\/strong><\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>async function findData() {\n  const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });\n\n  try {\n    await client.connect();\n    const db = client.db(dbName);\n    const collection = db.collection('users');\n\n    \/\/ \u67e5\u8be2\u6240\u6709\u7528\u6237\u6570\u636e\n    const users = await collection.find({}).toArray();\n    console.log(users);\n  } catch (err) {\n    console.error('Find operation failed:', err);\n  } finally {\n    await client.close();\n  }\n}\n\nfindData();<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>\u66f4\u65b0\u6570\u636e<\/strong><\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>async function updateData() {\n  const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });\n\n  try {\n    await client.connect();\n    const db = client.db(dbName);\n    const collection = db.collection('users');\n\n    \/\/ \u66f4\u65b0 Alice \u7684\u5e74\u9f84\n    const result = await collection.updateOne({ name: 'Alice' }, { $set: { age: 26 } });\n    console.log(`Matched ${result.matchedCount} document(s), modified ${result.modifiedCount} document(s)`);\n  } catch (err) {\n    console.error('Update operation failed:', err);\n  } finally {\n    await client.close();\n  }\n}\n\nupdateData();<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>\u5220\u9664\u6570\u636e<\/strong><\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>async function deleteData() {\n  const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });\n\n  try {\n    await client.connect();\n    const db = client.db(dbName);\n    const collection = db.collection('users');\n\n    \/\/ \u5220\u9664\u4e00\u4e2a\u540d\u4e3a Alice \u7684\u7528\u6237\n    const result = await collection.deleteOne({ name: 'Alice' });\n    console.log(`Deleted ${result.deletedCount} document(s)`);\n  } catch (err) {\n    console.error('Delete operation failed:', err);\n  } finally {\n    await client.close();\n  }\n}\n\ndeleteData();<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>4. \u5904\u7406\u9519\u8bef\u548c\u5f02\u5e38<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">\u5728 Node.js \u4e2d\u5904\u7406 MongoDB \u7684\u9519\u8bef\u548c\u5f02\u5e38\u975e\u5e38\u91cd\u8981\u3002\u4f60\u53ef\u4ee5\u4f7f\u7528 <code>try...catch<\/code> \u8bed\u53e5\u6765\u6355\u83b7\u6570\u636e\u5e93\u64cd\u4f5c\u4e2d\u7684\u5f02\u5e38\uff0c\u5e76\u8fdb\u884c\u76f8\u5e94\u5904\u7406\u3002<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">\u4f8b\u5982\uff0c\u4ee5\u4e0b\u4ee3\u7801\u6f14\u793a\u4e86\u5982\u4f55\u6355\u83b7\u6570\u636e\u5e93\u8fde\u63a5\u9519\u8bef\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>async function connectToMongoDB() {\n  const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });\n\n  try {\n    await client.connect();\n    console.log('Connected to MongoDB');\n  } catch (err) {\n    console.error('Failed to connect to MongoDB:', err.message);\n  } finally {\n    await client.close();\n  }\n}\n\nconnectToMongoDB();<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>5. \u4f7f\u7528 MongoDB \u7684\u805a\u5408\u529f\u80fd<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">MongoDB \u63d0\u4f9b\u4e86\u5f3a\u5927\u7684\u805a\u5408\u6846\u67b6\uff0c\u5141\u8bb8\u4f60\u8fdb\u884c\u66f4\u590d\u6742\u7684\u6570\u636e\u67e5\u8be2\u3001\u8fc7\u6ee4\u3001\u6392\u5e8f\u3001\u5206\u7ec4\u7b49\u64cd\u4f5c\u3002<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">\u4ee5\u4e0b\u662f\u4e00\u4e2a\u4f7f\u7528\u805a\u5408\u7ba1\u9053\u8fdb\u884c\u6570\u636e\u5206\u7ec4\u7684\u793a\u4f8b\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>async function aggregateData() {\n  const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });\n\n  try {\n    await client.connect();\n    const db = client.db(dbName);\n    const collection = db.collection('users');\n\n    \/\/ \u805a\u5408\u67e5\u8be2\uff0c\u6309\u57ce\u5e02\u5206\u7ec4\u5e76\u8ba1\u7b97\u6bcf\u4e2a\u57ce\u5e02\u7684\u7528\u6237\u6570\u91cf\n    const pipeline = &#91;\n      { $group: { _id: '$city', count: { $sum: 1 } } }\n    ];\n\n    const result = await collection.aggregate(pipeline).toArray();\n    console.log(result);\n  } catch (err) {\n    console.error('Aggregation failed:', err);\n  } finally {\n    await client.close();\n  }\n}\n\naggregateData();<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>\u603b\u7ed3<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\u4f7f\u7528 MongoDB Node.js \u9a71\u52a8\u8fde\u63a5\u5230\u6570\u636e\u5e93\uff0c\u901a\u8fc7 <code>MongoClient<\/code> \u7c7b\u548c\u8fde\u63a5\u5b57\u7b26\u4e32\u3002<\/li>\n\n\n\n<li>\u901a\u8fc7 <code>insertOne<\/code>\u3001<code>find<\/code>\u3001<code>updateOne<\/code> \u548c <code>deleteOne<\/code> \u7b49\u65b9\u6cd5\u6267\u884c\u5e38\u89c1\u7684 CRUD \u64cd\u4f5c\u3002<\/li>\n\n\n\n<li>\u4f7f\u7528 <code>aggregate<\/code> \u65b9\u6cd5\u8fdb\u884c\u66f4\u590d\u6742\u7684\u805a\u5408\u67e5\u8be2\u3002<\/li>\n\n\n\n<li>\u6355\u83b7\u548c\u5904\u7406\u8fde\u63a5\u548c\u67e5\u8be2\u4e2d\u7684\u5f02\u5e38\uff0c\u786e\u4fdd\u4ee3\u7801\u7684\u9c81\u68d2\u6027\u3002<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">\u901a\u8fc7\u8fd9\u4e9b\u6b65\u9aa4\uff0c\u4f60\u53ef\u4ee5\u8f7b\u677e\u5728 Node.js \u5e94\u7528\u4e2d\u5b9e\u73b0\u4e0e MongoDB \u7684\u8fde\u63a5\u548c\u6570\u636e\u64cd\u4f5c\u3002\u66f4\u591a\u8be6\u7ec6\u5185\u5bb9\u8bf7\u5173\u6ce8\u5176\u4ed6\u76f8\u5173\u6587\u7ae0\u3002<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">MongoDB\u5b98\u65b9Node.js\u9a71\u52a8\u7a0b\u5e8f\u7684\u5b98\u65b9\u6587\u6863\uff1a<a href=\"https:\/\/mongodb.github.io\/node-mongodb-native\/\" target=\"_blank\" rel=\"noreferrer noopener\">MongoDB Node.js Driver Documentation<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u8981\u5728 Node.js \u4e2d\u8fde\u63a5\u548c\u64cd\u4f5c MongoDB\uff0c\u4f60\u9700\u8981\u4f7f\u7528\u5b98\u65b9\u7684 MongoDB Node.js \u9a71\u52a8\u7a0b\u5e8f [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":2549,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[77],"tags":[],"class_list":["post-2475","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-mongodb"],"_links":{"self":[{"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/posts\/2475","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/comments?post=2475"}],"version-history":[{"count":1,"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/posts\/2475\/revisions"}],"predecessor-version":[{"id":2476,"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/posts\/2475\/revisions\/2476"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/media\/2549"}],"wp:attachment":[{"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/media?parent=2475"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/categories?post=2475"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/tags?post=2475"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}