CoffeeScript - MongoDB



MongoDB是一個跨平臺的文件型資料庫,提供高效能、高可用性和易擴充套件性。MongoDB基於集合和文件的概念。更多資訊請閱讀我們的MongoDB 教程

本章將學習如何使用CoffeeScript與MongoDB資料庫進行通訊。

安裝

MongoDB資料庫可以透過使用Node.js 2.0 MongoDB驅動程式與CoffeeScript整合。首先,您需要在您的系統中安裝MongoDB,請參考我們MongoDB教程的環境章節。

成功安裝MongoDB後,瀏覽其bin資料夾(如果您沒有設定路徑),然後啟動MongoDB服務,如下所示。

C:\Program Files\MongoDB\Server\3.2\bin> mongod

最後,透過在命令提示符中執行以下NPM命令來安裝MongoDB驅動程式及其依賴項。

npm install mongodb --save

連線到MongoDB

為了連線到MongoDB,首先使用MongoClient建立它,然後呼叫connect()函式。此函式接受url和回撥函式作為引數。

以下CoffeeScript程式碼展示瞭如何連線到MongoDB伺服器。如果MongoDB伺服器正在您的系統中執行,則此程式將建立與伺服器的連線。

#Requiring the Mongodb package
mongo = require 'mongodb'

#Creating a MongoClient object
MongoClient = mongo.MongoClient

#Preparing the URL
url = 'mongodb://:27017/testdb'

#Connecting to the server
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url
    #Close connection
    db.close()
  return

將上述程式碼儲存到名為connect_db.coffee的檔案中,並按如下所示執行它。如果資料庫成功建立,則會顯示以下訊息。

c:\> coffee connect_db.coffee
coffee connect_db.collection
Connection established to mongodb://:27017/testdb

建立集合

MongoDB中的集合儲存我們儲存在其中的文件。您可以使用collection()函式建立一個集合。此函式接受一個字串引數,表示我們要建立的集合的名稱。

以下CoffeeScript程式碼展示瞭如何在MongoDB中建立集合。如有任何錯誤,將在控制檯中顯示。

#Requiring the Mongodb package
mongo = require 'mongodb'

#Creating a MongoClient object
MongoClient = mongo.MongoClient

#Preparing the URL
url = 'mongodb://:27017/testdb'

#Connecting to the server
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url
	
    #Create collection
    col = db.collection('My_collection')
    console.log "Collection created successfully."
	
    #Close connection
    db.close()
  return

將上述程式碼儲存到名為create_collection.coffee的檔案中,並按如下所示執行它。如果集合成功建立,則會顯示以下訊息。

c:/> coffee create_collection.coffee
Connection established to mongodb://:27017/testdb
Collection created successfully.

插入文件

您可以在MongoDB的集合中插入文件,您需要透過傳遞需要插入的文件列表作為引數來呼叫名為insert()的函式。

以下CoffeeScript程式碼展示瞭如何在名為My_collection的集合中插入文件。如有任何錯誤,將在控制檯中顯示。

#Sample JSON Documents
doc1 = {name: 'Ram', age: 26, city: 'Hyderabad'}
doc2 = {name: 'Rahim', age: 27, city: 'Banglore'}
doc3 = {name: 'Robert', age: 28, city: 'Mumbai'}

#Requiring the Mongodb package
mongo = require 'mongodb'

#Creating a MongoClient object
MongoClient = mongo.MongoClient

#Preparing the URL
url = 'mongodb://:27017/testdb'

#Connecting to the server
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url  
  #Creating collection
  col = db.collection('My_collection')
	
  #Inserting documents
  col.insert [doc1,doc2,doc3], (err, result) ->
    if err
      console.log err
    else
      console.log "Documents inserted successfully"
    #Close connection
    db.close()
    return
  return

將上述程式碼儲存到名為insert_documents.coffee的檔案中,並按如下所示執行它。如果文件成功插入,則會顯示以下訊息。

c:/> coffee insert_documents.coffee
Connection established to mongodb://:27017/testdb
Documents inserted successfully

讀取文件

您可以使用名為find()的函式檢索儲存在MongoDB中的文件。以下CoffeeScript程式碼展示瞭如何檢索儲存在MongoDB中的記錄。

#Requiring the Mongodb package
mongo = require 'mongodb'

#Creating a MongoClient object
MongoClient = mongo.MongoClient

#Preparing the URL
url = 'mongodb://:27017/testdb'

#Connecting to the server
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url	
	#Creating collection object
    col = db.collection('My_collection')    
    #Inserting Documents
    col.find({name: 'Ram'}).toArray (err, result)->
      if err
        console.log err
      else 
      console.log 'Found:', result			
      #Closing connection
      db.close()
      return
  return

將上述程式碼儲存到名為read_documents.coffee的檔案中,並按如下所示執行它。此程式檢索指定集合中所需的文件並顯示它,如下所示。

C:\> coffee read_documents.coffee
Connection established to mongodb://:27017/testdb
Found: [ { _id: 56e269c10478809c3009ad1e,
    name: 'Ram',
    age: 26,
    city: 'Hyderabad' } ]

您還可以透過執行不向其傳遞任何引數的find()函式來讀取特定集合中所有現有的文件,如下所示。

#Requiring the Mongodb package
mongo = require 'mongodb'

#Creating a MongoClient object
MongoClient = mongo.MongoClient

#Preparing the URL
url = 'mongodb://:27017/testdb'

#Connecting to the server
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url	
	#Creating collection object
    col = db.collection('My_collection')    
    #Reading all Documents
    col.find().toArray (err, result)->
      if err
        console.log err
      else 
      console.log 'Found:', result			
      #Closing connection
      db.close()
      return
  return

將上述程式碼儲存到名為read_all_documents.coffee的檔案中,並按如下所示執行它。此程式檢索指定集合中的所有文件並顯示它,如下所示。

C:\> coffee read_all_documents.coffee
Connection established to mongodb://:27017/testdb
Found: [ { _id: 56e2c5e27e0bad741a68c03e,
    name: 'Ram',
    age: 26,
    city: 'Hyderabad' },
  { _id: 56e2c5e27e0bad741a68c03f,
    name: 'Rahim',
    age: 27,
    city: 'Banglore' },
  { _id: 56e2c5e27e0bad741a68c040,
    name: 'Robert',
    age: 28,
    city: 'Mumbai' } ]

更新文件

您可以使用名為update()的函式更新儲存在MongoDB中的文件。以下CoffeeScript程式碼展示瞭如何更新儲存在MongoDB中的記錄。

#Get mongo client object
MongoClient = require('mongodb').MongoClient
#Connecting to mongodb
url = 'mongodb://:27017/testdb'
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url	
	#Creating collection
    col = db.collection('My_collection')
    #Reading Data
    col.update {name:'Ram'},{$set:{city:'Delhi'}},(err, result)->
      if err
        console.log err
      else 
      console.log "Document updated"    
      
      #Closing connection
      db.close()
	  return
  return

此程式將名為Ram的員工的城市從Hyderabad更新為Delhi。

將上述程式碼儲存到名為update_documents.coffee的檔案中,並按如下所示執行它。此程式檢索指定集合中的文件並顯示它,如下所示。

C:\> coffee update_documents.coffee
Connection established to mongodb://:27017/testdb
Document updated

更新後,如果您執行read_documents.coffee程式,您將觀察到名為Ram的人的城市名稱已從Hyderabad更新為Delhi

C:\> coffee Read_all_documents.coffee
Connection established to mongodb://:27017/testdb
Found: [ { _id: 56e2c5e27e0bad741a68c03e,
    name: 'Ram',
    age: 26,
    city: 'Delhi' },
  { _id: 56e2c5e27e0bad741a68c03f,
    name: 'Rahim',
    age: 27,
    city: 'Banglore' },
  { _id: 56e2c5e27e0bad741a68c040,
    name: 'Robert',
    age: 28,
    city: 'Mumbai' } ]

刪除文件

您可以使用remove()函式刪除集合中的所有文件。以下CoffeeScript程式碼展示瞭如何刪除儲存在MongoDB中的所有記錄。

#Get mongo client object
MongoClient = require('mongodb').MongoClient
#Connecting to mongodb
url = 'mongodb://:27017/testdb'
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url	
	#Creating collection
    col = db.collection('My_collection')
    #Deleting Data
    col.remove()
    console.log "Document deleted"
      
    #Closing connection
    db.close()	  
  return

將上述程式碼儲存到名為delete_documents.coffee的檔案中,並按如下所示執行它。此程式刪除指定集合中的所有文件,並顯示以下訊息。

C:\> coffee delete_documents.coffee
Connection established to mongodb://:27017/testdb
Document deleted

刪除後,如果您執行read_documents.coffee程式,您將得到一個空集合,如下所示。

C:\> coffee Read_all_documents.coffee
Connection established to mongodb://:27017/testdb
Found: [ ]
廣告