這篇文章主要介紹了使用Nodejs連接mongodb資料庫的實作程式碼,需要的朋友可以參考下
一個簡單的nodejs連接mongodb範例,來自mongodb官方範例
#1. 建立package.json
首先,建立我們的工程目錄connect-mongodb,並作為我們的目前目錄
mkdir connect-mongodb cd connect-mongodb
輸入npm init
指令建立package.json
npm init
然後,安裝mongodb的nodejs版本driver
npm install mongodb --save
mongodb驅動套件將會安裝到目前目錄下的node_modules中
#2 . 啟動MongoDB伺服器
安裝MongoDB並啟動MongoDB資料庫服務,可參考我之前的文章,或MongoDB官方文件
3. 連接MongoDB
建立一個app.js文件,並加入以下程式碼來連接伺服器位址為192.168.0.243,mongodb連接埠為27017上名稱為myNewDatabase的資料庫
var MongoClient = require('mongodb').MongoClient, assert = require('assert'); // Connection URL var url = 'mongodb://192.168.0.243:27017/myNewDatabase'; MongoClient.connect(url,function(err,db){ assert.equal(null,err); console.log("Connection successfully to server"); db.close(); });
在命令列輸入以下命令執行app.js
#node app.js
4.插入文件
在app.js中加入以下程式碼,使用insertMany方法新增3個文件到documents集合中
##
var insertDocuments = function(db, callback){ // get ths documents collection var collection = db.collection('documents'); // insert some documents collection.insertMany([ {a:1},{a:2},{a:3} ],function(err,result){ assert.equal(err,null); assert.equal(3,result.result.n); assert.equal(3,result.ops.length); console.log("Inserted 3 documents into the collection"); callback(result); }); };#insert指令傳回一個包含下列屬性的物件:
- result MongoDB傳回的文檔結果
- ops 新增了_id欄位的文檔
- connection 執行插入操作所使用的connection
#
var MongoClient = require('mongodb').MongoClient , assert = require('assert'); // Connection URL var url = 'mongodb://localhost:27017/myproject'; // Use connect method to connect to the server MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected successfully to server"); insertDocuments(db, function() { db.close(); }); });在命令列中使用node app.js執行
#5.查詢所有文件
新增findDocuments函數var findDocuments = function(db,callback){ // get the documents collection var collection = db.collection('documents'); // find some documents collection.find({}).toArray(function(err,docs){ assert.equal(err,null); console.log("Found the following records"); console.log(docs); callback(docs); }); };findDocuments函數查詢了所有'documents'集合中所有的文檔,將此函數新增至MongoClient.connect的回呼函數
var MongoClient = require('mongodb').MongoClient , assert = require('assert'); // Connection URL var url = 'mongodb://localhost:27017/myproject'; // Use connect method to connect to the server MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to server"); insertDocuments(db, function() { findDocuments(db, function() { db.close(); }); }); });
6. 使用篩選條件(query filter)查詢文件##查詢'a' :3的文件
var findDocuments = function(db, callback) { // Get the documents collection var collection = db.collection('documents'); // Find some documents collection.find({'a': 3}).toArray(function(err, docs) { assert.equal(err, null); console.log("Found the following records"); console.log(docs); callback(docs); }); }
#7. 更新文件##
var updateDocument = function(db,callback){ // get the documents collection var collection = db.collection('documents'); // update document where a is 2, set b equal to 1 collection.updateOne({a:2},{ $set:{b:1} },function(err,result){ assert.equal(err,null); assert.equal(1,result.result.n); console.log("updated the document with the field a equal to 2"); callback(result); }); };updateDocument方法更新滿足條件a為2的第一個文檔,新增一個b屬性,並將其設為1。 將updateDocument方法加入MongoClient.connect方法的回呼中
MongoClient.connect(url,function(err,db){ assert.equal(null,err); console.log("Connection successfully to server"); insertDocuments(db,function(){ updateDocument(db,function(){ db.close(); }); }); });
var removeDocument = function(db,callback){ // get the documents collection var collection = db.collection('documents'); // remove some documents collection.deleteOne({a:3},function(err,result){ assert.equal(err,null); assert.equal(1,result.result.n); console.log("removed the document with the field a equal to 3"); callback(result); }); };加入到app.js中
var MongoClient = require('mongodb').MongoClient , assert = require('assert'); // Connection URL var url = 'mongodb://localhost:27017/myproject'; // Use connect method to connect to the server MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected successfully to server"); insertDocuments(db, function() { updateDocument(db, function() { removeDocument(db, function() { db.close(); }); }); }); });
9. 建立索引
索引能夠改善應用程式的效能。下面你程式碼在'a'屬性上加入索引var indexCollection = function(db,callback){ db.collection('documents').createIndex({ a:1 },null,function(err,results){ console.log(results); callback(); }); };#更新app.js
MongoClient.connect(url,function(err,db){ assert.equal(null,err); console.log("Connection successfully to server"); insertDocuments(db,function(){ indexCollection(db,function(){ db.close(); }); }); });
以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網! 相關推薦:
以上是使用Nodejs連接mongodb資料庫的實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JavaScript字符串替換方法詳解及常見問題解答 本文將探討兩種在JavaScript中替換字符串字符的方法:在JavaScript代碼內部替換和在網頁HTML內部替換。 在JavaScript代碼內部替換字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 該方法僅替換第一個匹配項。要替換所有匹配項,需使用正則表達式並添加全局標誌g: str = str.replace(/fi

因此,在這裡,您準備好了解所有稱為Ajax的東西。但是,到底是什麼? AJAX一詞是指用於創建動態,交互式Web內容的一系列寬鬆的技術。 Ajax一詞,最初由Jesse J創造

本文討論了在瀏覽器中優化JavaScript性能的策略,重點是減少執行時間並最大程度地減少對頁面負載速度的影響。

本文討論了使用瀏覽器開發人員工具的有效JavaScript調試,專注於設置斷點,使用控制台和分析性能。

將矩陣電影特效帶入你的網頁!這是一個基於著名電影《黑客帝國》的酷炫jQuery插件。該插件模擬了電影中經典的綠色字符特效,只需選擇一張圖片,插件就會將其轉換為充滿數字字符的矩陣風格畫面。快來試試吧,非常有趣! 工作原理 插件將圖片加載到畫布上,讀取像素和顏色值: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data 插件巧妙地讀取圖片的矩形區域,並利用jQuery計算每個區域的平均顏色。然後,使用

本文將引導您使用jQuery庫創建一個簡單的圖片輪播。我們將使用bxSlider庫,它基於jQuery構建,並提供許多配置選項來設置輪播。 如今,圖片輪播已成為網站必備功能——一圖胜千言! 決定使用圖片輪播後,下一個問題是如何創建它。首先,您需要收集高質量、高分辨率的圖片。 接下來,您需要使用HTML和一些JavaScript代碼來創建圖片輪播。網絡上有很多庫可以幫助您以不同的方式創建輪播。我們將使用開源的bxSlider庫。 bxSlider庫支持響應式設計,因此使用此庫構建的輪播可以適應任何

數據集對於構建API模型和各種業務流程至關重要。這就是為什麼導入和導出CSV是經常需要的功能。在本教程中,您將學習如何在Angular中下載和導入CSV文件


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

SublimeText3 Linux新版
SublimeText3 Linux最新版