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://localhost: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://localhost: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://localhost: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://localhost:27017/testdb
Collection created successfully.

插入文档

您可以将文档插入到MongoDB中的集合中,您需要调用名为

以下CoffeeScript代码显示如何将文档插入名为

#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://localhost: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://localhost: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://localhost: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://localhost: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://localhost: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://localhost: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://localhost: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的员工城市从海得拉巴更新为德里.

将上述代码保存在名为 update_documents.coffee 的文件中,并按如下所示执行.此程序检索指定集合中的文档并显示如下所示.

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

更新后,如果执行 read_documents.coffee 程序,然后您将看到名为Ram的人的城市名称从 Hyderabad 更新为 Delhi .

C:\> coffee Read_all_documents.coffee
Connection established to mongodb://localhost: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' } ]

删除文档

您可以使用删除()功能删除集合中的所有文档.以下CoffeeScript代码显示了如何删除存储在MongoDB中的所有记录.

#Get mongo client object
MongoClient = require('mongodb').MongoClient
#Connecting to mongodb
url = 'mongodb://localhost: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://localhost:27017/testdb
Document deleted

删除后,如果执行 read_documents.coffee 程序,然后您将获得一个空集合,如下所示.

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