ColdFusion and MongoDB

Overview

MongoDB is a cross-platform document-based NoSQL database. It uses JSON/BSON like documents with schema.

  • MongoDB stores data in flexible, JSON-like documents, meaning fields can vary from document to document and data structure can be changed over time.
  • The document model maps to the objects in your application code, making data easy to work with.
  • Ad hoc queries, indexing, and real time aggregation provide powerful ways to access and analyze your data.
  • MongoDB is a distributed database at its core, so high availability, horizontal scaling, and geographic distribution are built in and easy to use.

Features of MongoDB

The following are some of the features of MongoDB.

  • Queries: MongoDb supports ad-hoc queries and document-based queries. It also supports searching by field, range queries, and regular expressions.
  • Indexing: You can index any field in the document.
  • Replication: MongoDB supports master slave replication. MongoDB uses native application to maintain multiple copies of data.
  • Multiple Servers: The database can run over multiple servers. Data is duplicated to bullet proof the system in case of hardware failure.
  • Auto-Sharding: This process distributes data across multiple physical partitions called shards. Due to sharding, MongoDB has an automatic load-balancing feature.
  • MapReduce: Supports MapReduce and flexible aggregation tools.

For more information on the features of MongoDB, see the MongoDB official website.

Install MongoDB

To install MongoDB for your OS, see the MongoDB download center.

MongoDB vs RDBMS – a comparison

RDBMS

MongoDB

Database

Database

Table

Collection

Tuple/Row

Document

column

Field

Table Join

Embedded Documents

Primary Key

Primary Key (Default key _id provided by mongodb itself)

In MongoDB, ObjectIds or primary keys are 12 bytes long, made up of several 2-4 byte chains. The following values make up the full 12 byte combination:

  • a 4-byte value representing the seconds since the Unix epoch
  • a 3-byte machine identifier
  • a 2-byte process id
  • a 3-byte counter, starting with a random value

Install cfmongodb package

Adobe ColdFusion (2021 release) is modularized, if you are only using the ZIP installer. By default, the module for MongoDB is not installed. The first step is to install the MongoDB package in ColdFusion. For the purpose of convenience though, this module is pre-installed in case of the GUI installer. 

Note: If you are using the GUI installer, the packages are pre-installed.

The package for SQS is called cfmongodb.

To install the package cfmongodb, follow the steps below:

  1. Navigate to <CF_HOME>/cfusion/bin.
  2. Enter the command:
    1. Windows: cfpm.bat
    2. Linux: cfpm.sh
  3. Enter the command, install cfmongodb.

Wait for the MongoDB package to get installed.

Install from ColdFusion Administrator

  1. In ColdFusion Administrator > Package Manager, expand the section Available Packages.
  2. From the list of packages, select cfmongodb.
  3. Click Install.

Integration with ColdFusion

In Application.cfc, in the property datasources, create a connection to MongoDB by specifying the MongoDB host (server/localhost) and port, as shown below:

component { 
 this.name = "mongotest77123"; 
 this.serialization.preservecaseforstructkey=true 
 this.enableNullSupport=true 
 
 this.datasources = {  
  "local"= { 
   type="mongodb" 
  }, 
  "mymongodb"= { 
   type="mongodb", 
   host="mongodb://127.0.0.1:27017/", 
   "init"= true 
  } 
 } 
}

Create MongoDB datasource via ColdFusion Administrator

In ColdFusion Administrator, click Data & Services > NoSQL Data Sources.

Add and manage your NoSql data source connections and Data Source Names (DSNs).

Enter the name of the datasource and choose Driver as MongoDB.

Click Add.

Add the configuration details, such as, host, port, Enable SSL, etc. For more information, see the NoSQL options.

Create MongoDB datasource via Admin APIs

CFC: CFIDE.adminapi.nosql_datasource

setMongoDataSource

Creates or modifies a MongoDb datasource.

Syntax

public void setMongoDataSource ( required string name, required string type, required string host, string port="27017", string replicaSet, boolean ssl, boolean dnsSeedList, string authMechanism, string username, string password, string authSource, string gssapiServiceName, string readConcern, string readPreference, string w, string wtimeout, boolean j, string connectTimeout, string maxPoolSize, string minPoolSize, string maxConnectionLifeTime, string maxConnectionIdleTime, string maxWaitQueueTimeout, string maxWaitQueueSize, string heartbeatFrequency, string minHeartbeatFrequency 

Parameters

  • name: string, required, name - ColdFusion datasource name.
  • type: string, required, type - Database type.
  • host: string, required, host - Database server host name or IP address.
  • port: string, optional, port - Port that is used to access the database server. (default 27017)
  • replicaSet: string, optional, replicaSet - Specifies the name of the replica set, if the mongod is a member of a replica set.
  • ssl: boolean, optional, ssl - Whether to enable or disable TLS/SSL for the connection
  • dnsSeedList: boolean, optional, dnsSeedList
  • authMechanism: string, optional, authMechanism
  • username: string, optional, username
  • password: string, optional, password
  • authSource: string, optional, authSource
  • gssapiServiceName: string, optional,  - Specify the GSSAPI service name if the authMechanism is gssapi.
  • readConcern: string, optional, readConcern - Read Concern allows clients to choose a level of isolation for their reads from replica sets.
  • readPreference: string, optional, readPreference - Read preferences describe the behavior of read operations with regards to replica sets.
  • w: string, optional, w - The w option requests acknowledgement that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags.
  • wtimeout: string, optional, wtimeout - This specifies a time limit, in milliseconds, for the write concern.
  • j: boolean, optional, j - The journal option requests acknowledgement from MongoDB that the write operation has been written to the journal.
  • connectTimeout: string, optional, connectTimeout - The time in milliseconds to attempt a connection before timing out.
  • maxPoolSize: string, optional, maxPoolSize - The maximum number of connections in the connection pool.
  • minPoolSize: string, optional, minPoolSize - The minimum number of connections in the connection pool.
  • maxConnectionLifeTime: string, optional, maxConnectionLifeTime - The maximum lifetime of a connection.
  • maxConnectionIdleTime: string, optional, maxConnectionIdleTime - The maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed.
  • maxWaitQueueTimeout: string, optional, maxWaitQueueTimeout
  • maxWaitQueueSize: string, optional, maxWaitQueueSize - The maximum number of connections in the connection pool.
  • heartbeatFrequency: string, optional, heartbeatFrequency - Heartbeat frequency controls when the driver checks the state of the MongoDB deployment.
  • minHeartbeatFrequency: string, optional, minHeartbeatFrequency

Example

<cfscript> 
  // Create an object of administrator component and call the login method 
  adminObj = createObject("component","cfide.adminapi.administrator"); 
  adminObj.login("admin"); 
  
  // Create an object of datasource component 
  dsnObj = createObject("component","cfide.adminapi.nosql_datasource"); 
  
  // Setting up the parameter values for mongodb datasource 
  mongoDSN.name  = "mongo1" 
  mongoDSN.type = "mongodb" 
  mongoDSN.host = "127.0.0.1" 
  mongoDSN.port = "27017" 
  mongoDSN.caseSensitivity = "false" 
  
  // Create MongoDB datasource 
  mResponse=dsnObj.setMongoDataSource(mongoDSN.name,mongoDSN.type,mongoDSN.host, 
  mongoDSN.port,mongoDSN.caseSensitivity) 
</cfscript>

getDataSources

Returns a structure containing all data sources or a specified data source.

Syntax

public any getDatasources (dsnName)

Parameters

  • dsnName: any, optional, dsnName - The name of the data source for which a structure is returned.

Example

<cfscript> 
  // Create an object of administrator component and call the login method 
  adminObj = createObject("component","cfide.adminapi.administrator"); 
  adminObj.login("admin"); 
  
  // Create an object of datasource component 
  dsnObj = createObject("component","cfide.adminapi.nosql_datasource"); 
  
  res=dsnObj.getDatasources() 
  writeDump(res) 
</cfscript>

deleteMongoDatasource

Deletes the specified data source.

Syntax

public void deleteMongoDatasource ( required dsnName )

Parameters

  •  dsnName: any, required, dsnName - The name of the data source to be deleted.

Example

<cfscript> 
  // Create an object of administrator component and call the login method 
  adminObj = createObject("component","cfide.adminapi.administrator"); 
  adminObj.login("admin"); 
  
  // Create an object of datasource component 
  dsnObj = createObject("component","cfide.adminapi.nosql_datasource"); 
  
  // Get datasource 
  res=dsnObj.getDatasources() 
  writedump(res) 
  
  // Delete datasource ds1 
  dsnObj.deleteMongoDatasource(res.ds1.name) 
   
</cfscript>

verifyMongoDatasource

Verifies a given data source name.

Syntax

public Any verifyMongoDatasource ( required dsnName )

Parameters

  • dsnName: any, required, dsnName - Name that ColdFusion uses to connect to the data source.

Example

<cfscript> 
  // Create an object of administrator component and call the login method 
  adminObj = createObject("component","cfide.adminapi.administrator"); 
  adminObj.login("admin"); 
  
  // Create an object of datasource component 
  dsnObj = createObject("component","cfide.adminapi.nosql_datasource"); 
  
  // Get datasource 
  res=dsnObj.getDatasources() 
  writedump(res) 
  
  // Verify datasource ds1 
  verifyRes=dsnObj.verifyMongoDatasource(res.ds1.name)  
  writeDump(verifyRes) 
</cfscript> 

Add datasource using CFSetup

add nosql name=testset mongoport=27017 mongoHost=see-wv-a403 driverName=MONGODB maxStalenessSeconds=2000 MAXWAITQUEUETIMEOUT=2000 MAXWAITQUEUESIZE=10 MAXPOOLSIZE=20 MAXCONNECTIONLIFETIME=2000 HEARTBEATFREQUENCY=10  MAXCONNECTIONIDLETIME=2000 MINHEARTBEATFREQUENCY=2 CONNECTTIMEOUT=2000 READPREFERENCE=PRIMARY SSL=YES  REPLICASET=replica READCONCERN=majority dnsSeedList=true <alias>

Collection

A collection is equivalent to a table of a relational db. A collection stores documents that do not conform to a structure. This is because MongoDB is a schema-free database.

Create a collection

To create a collection, you must create a MongoDB database object and create the collection inside the db. A db can consist of multiple collections. See the code below for the syntax:

<cfscript> 
 // mymongodb is the name of the connection to MongoDB, defined in Application.cfc 
  
 db = getMongoService("mymongodb").db("newdb") // create a db 
 db.createCollection("Coll_1") // create a collection 
 db.createCollection("Coll_2") // create another collection 
</cfscript>

Create a document

Once you create a collection, you must insert one or more documents into the collection.

Insert one document

Here is how you can insert a single document in a collection using the insert method.

<cfscript> 
 db = getmongoservice("mymongodb").db("newdb") // create a db 
 db.createCollection("newcolThree") // create a collection 
 // insert a single document 
 db.newcolThree.insert({ 
  "_id": 1, 
  "name":"John Lennon", 
  "band":"Beatles" 
 }) 
</cfscript> 

Note: If you do not explicitly set an Objectid set when defining the document, MongoDB, by default, assigns one to the document. The snippet contains an explicitly set Objectid, which gets displayed.

Insert many documents

You can insert multiple documents, as an array of structs, in a collection using the insertMany method.

<cfscript> 
 db = getmongoservice("mymongodb").db("newdb") // create a db 
 db.newcolThree.drop() // drop the collection 
 db.createCollection("newcolThree") // create a collection 
 // insert a single document 
 db.newcolThree.insert({ 
  "_id": 1, 
  "name":"John Lennon", 
  "band":"Beatles" 
 }) 
 // insert another document 
 db.newcolThree.insertOne({ 
  "_id": 2, 
  "name":"Paul McCartney", 
  "band":"Beatles" 
 }) 
 // insert many documents 
 db.newcolThree.insertMany([ 
  { 
   "_id": 3, 
   "name":"George Harrison", 
   "band":"Beatles" 
  }, 
  { 
   "_id": 4, 
   "name":"Ringo Starr", 
   "band":"Beatles" 
  } 
 ]) 
</cfscript>

Create a capped collection

Capped collections are fixed-size circular collections that follow the insertion order to support high performance for create, read, and delete operations. By circular, it means that when the fixed size allocated to the collection is exhausted, it will start deleting the oldest document in the collection without providing any explicit commands.

Capped collections restrict updates to the documents if the update results in increased document size. Since capped collections store documents in the

order of the disk storage, it ensures that the document size does not increase the size allocated on the disk. Capped collections are best for storing log information, cache data, or any other high volume data.

For more information, see Capped collections in MongoDB.

<cfscript> 
 db = getmongoservice("mymongodb").db("newdb") // create a db 
 // create a capped collection by passing capped flag as true,  
 // size of collection, 
 // and max number of documents 
 db.createCollection("cappedLogCollection",{capped:true,size:10000,max:1000}) 
</cfscript>

If you set capped to true, you must also set a maximum size in the size field.

To check if a collection is capped, use the method isCapped.

<cfscript> 
 db = getmongoservice("mymongodb").db("newdb") // create a db 
 ifCapped=db.cappedLogCollection.isCapped() 
 writeOutput("Is collection capped: "& ifCapped) 
</cfscript>

To convert an existing non-capped collection to a capped one, use the code below. You can use the convertToCapped method to convert to a capped collection.

<cfscript> 
 db = getmongoservice("mymongodb").db("newdb") // create a db 
 db.convertToCapped.drop() 
 // create an un-capped collection 
 db.createCollection("convertToCapped") // create a collection 
 //convert an existing non-capped collection to a capped collection 
 db.convertToCapped({"convertToCapped":"posts",size:10000}) 
</cfscript>

Query a collection

The find method selects documents in a collection or returns a cursor to the selected documents.

The find method has two parameters, query struct and projection, both optional. For more information, see the doc for find.

In the sample below, the find method does not use any parameter.

<cfscript> 
 db = getmongoservice("mymongodb").db("newdb") // create a db 
 db.createCollection("colFindDemo") // create a collection 
 db.colFindDemo.insertMany([ 
   
   { "_id" : 1, "name" : "Ian Gillan", "instrument" : "Vocals","born": 1945 }, 
   { "_id" : 2, "name" : "Ian Paice", "instrument" : "Drums", "born" : 1948 }, 
   { "_id" : 3, "name" : "Roger Glover", "instrument" : "Bass", "born" : 1945 }, 
   { "_id" : 4, "name" : "Steve Morse", "instrument" : "Guitar", "born" : 1954 }, 
   { "_id" : 5, "name" : "Don Airey", "instrument" : "Keyboards", "born" : 1948 }, 
   { "_id" : 6, "name" : "Jeff Martin", "instrument" : "Vocals", "born" : 1969 }, 
   { "_id" : 7, "name" : "Jeff Burrows", "instrument" : "Drums", "born" : 1968 }, 
   { "_id" : 8, "name" : "Stuart Chatwood", "instrument" : "Bass", "born" : 1969 } 
   
 ]) 
 // return all documents 
 db.colFindDemo.find() 
</cfscript>

To find the document(s) that match a query criteria, for example, where _id equals 4, see the sample below:

<cfscript>

       db.colFindDemo.find({"_id":4})

</cfscript>

Another example that matches the criteria where instrument equals drums is shown below:

<cfscript>

       db.colFindDemo.find({"instrument":"Drums"})

</cfscript> 

Find using query operators

The examples below show the usage of query operators to find documents in a collection.

<cfscript>

       df.colFindDemo.find({"_id":{$gt:4}}) // find _ids greater than 4

</cfscript>

<cfscript>

       df.colFindDemo.find({"instrument":{$regex:"^B"}}) // find instruments that start with B

</cfscript>

<cfscript>

       db.colFindDemo.find({"name":{$in:["Ian Gillan","Ian Paice"]}}) // find documents that match the names

</cfscript>

<cfscript>

       db.colFindDemo.find({"born":{$all:[1948]}}) // find documents that match born, which contains the year 1948

</cfscript>

Update a collection

You can update a collection using these methods:

  • update
  • updateOne
  • updateMany

update

The update method modifies an existing document or documents in a collection. For more information, see update method docs.

<cfscript> 
 db = getmongoservice("mymongodb").db("newdb") // create a db 
 db.colUpdDemo.drop() 
 db.createCollection("colUpdDemo") // create a collection 
 db.colUpdDemo.insertMany([ 
  { 
    "_id":1, 
    "product_name": "sildenafil citrate", 
    "supplier": "Wisozk Inc", 
    "quantity": 261, 
    "unit_cost": "$10.47" 
  },  
  { 
    "_id":2, 
    "product_name": "Mountain Juniperus ashei", 
    "supplier": "Keebler-Hilpert", 
    "quantity": 292, 
    "unit_cost": "$8.74" 
  },  
  { 
    "_id":3, 
    "product_name": "Dextromathorphan HBr", 
    "supplier": "Schmitt-Weissnat", 
    "quantity": 211, 
    "unit_cost": "$20.53" 
  } 
]) 
 // increment quantity by 10 for _id:1 
 db.colUpdDemo.update({"_id":1},{$inc:{"quantity":10}}) 
 // update unit cost from 8.74 to 10.74 
 db.colUpdDemo.update({"_id":2},{$set:{"unit_cost": "$10.74"}}) 
</cfscript>

update with pipeline

The aggregation pipeline is a framework that is modeled on the idea of data processing via pipelines in stages. Documents enter a multi-stage pipeline that transforms the documents into aggregated results.

For more information, see Aggregated pipelines in MongoDB.

<cfscript> 
 db = getmongoservice("mymongodb").db("imdb"); 
 db.members.drop() 
 
 res = db.members.insertMany([ 
     { "_id" : 1, "member" : "abc123", "status" : "A", "points" : 2, "misc1" : "note to self: confirm status", "misc2" : "Need to activate" }, 
     { "_id" : 2, "member" : "xyz123", "status" : "A", "points" : 60, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" } 
 ]) 
 
 writedump(res) 
 
 db.members.find().foreach((s) => { 
 writedump(s) 
 }) 
 
 writeoutput("apply update pipeline") 
 
 res = db.members.update( 
    { }, 
    [ 
      { $set: { status: "Modified", comments: [ "$misc1", "$misc2" ] } }, 
      { $unset: [ "misc1", "misc2" ] } 
    ], 
    { multi: true } 
 ) 
 
 writedump(res) 
 
 db.members.find().foreach((s) => { 
  writedump(s) 
}) 
 
 db.members.drop() 
</cfscript>

updateOne

The method, based on a specified filter, updates a single document in a collection. For more information, see updateOne method docs.

<cfscript> 
 db = getmongoservice("mymongodb").db("newdb") // create a db 
 db.colUpdDemo.drop() 
 db.createCollection("colUpdDemo") // create a collection 
 db.colUpdDemo.insertMany([ 
  { 
    "_id":1, 
    "product_name": "sildenafil citrate", 
    "supplier": "Wisozk Inc", 
    "quantity": 261, 
    "unit_cost": "$10.47", 
    "stock":10000 
  },  
  { 
    "_id":2, 
    "product_name": "Mountain Juniperus ashei", 
    "supplier": "Keebler-Hilpert", 
    "quantity": 292, 
    "unit_cost": "$8.74", 
    "stock":15000 
  },  
  { 
    "_id":3, 
    "product_name": "Dextromathorphan HBr", 
    "supplier": "Schmitt-Weissnat", 
    "quantity": 211, 
    "unit_cost": "$20.53", 
    "stock":20000 
  } 
]) 
    db.colUpdDemo.updateOne({"supplier": "Keebler-Hilpert"},{$set:{"stock":16000}}) 
</cfscript> 

Using Try-Catch

Using try-catch statements, you can handle certain exceptions when a certain value is missing or incorrect. For example,

<cfscript> 
 db = getmongoservice("mymongodb").db("newdb") // create a db 
 db.colUpdOneDemo.drop() 
 db.createCollection("colUpdOneDemo") // create a collection 
 db.colUpdOneDemo.insertMany([ 
  { "_id" : 1, "name" : "Central Perk Cafe", "Borough" : "Manhattan" }, 
  { "_id" : 2, "name" : "Rock A Feller Bar and Grill", "Borough" : "Queens", "violations" : 2 }, 
  { "_id" : 3, "name" : "Empire State Pub", "Borough" : "Brooklyn", "violations" : 0 } 
 ]) 
 try { 
    db.restaurant.updateOne( 
        { "name" : "Central Perk Cafe New" }, // specify incorrect value 
        { $set: { "violations" : 3 } } 
    ) 
 }  
 catch (any e) { 
    WriteOutput("Error: " & e.message) 
} 
</cfscript>

updateMany

The method, based on a specified filter, updates multiple documents in a collection. For more information, see updateMany method docs.

<cfscript> 
       db = getmongoservice("mymongodb").db("newdb") // create a db 
       db.colUpdManyDemo.drop() 
       db.createCollection("colUpdManyDemo") // create a collection 
       db.colUpdManyDemo.insertMany([ 
             { 
             "_id":1, 
             "product_name": "sildenafil citrate", 
             "supplier": "Wisozk Inc", 
             "quantity": 261, 
             "unit_cost": "$10.47", 
             "stock":10000 
             },  
             { 
             "_id":2, 
             "product_name": "Mountain Juniperus ashei", 
             "supplier": "Keebler-Hilpert", 
             "quantity": 292, 
             "unit_cost": "$8.74", 
             "stock":15000 
             },  
             { 
             "_id":3, 
             "product_name": "Dextromathorphan HBr", 
             "supplier": "Schmitt-Weissnat", 
             "quantity": 211, 
             "unit_cost": "$20.53", 
             "stock":20000 
             } 
       ]) 
       // update more than one document based on the specified filter 
       db.collection.updateMany( {"quantity" : {$gt: 250 }}, {$set: { "stock" : 50000 } } ); 
</cfscript>

Support for advanced data types

Employee.cfc

component accessors="true" 
{ 
    property string empName; 
    property numeric age; 
    property string dept; 
}

Serialize CFC object

<cfscript> 
    // Retrieve database connection 
    db = getmongoservice("mymongodb").db("cf_local") 
    collection = db.students 
    emp = new Employee({empName="James", age=26, dept="000"}); 
    serializedStr = serializeJSON(emp); 
    collection.insertMany([{ 
        key: serializedStr, 
        name: "John Doe" 
    }]); 
    //Read from mongo 
    result = collection.find({"name" : {$eq:   "John Doe"}}).first() 
   
    fileDataFromMongo = structFind(result, "key"); 
    fileInJSON =  DeserializeJSON(fileDataFromMongo); 
</cfscript>

CFC JSON

test.cfc

{ 
     name="John", 
     age="26" 
}

cfcjson.cfm

<cfscript> 
    // Retrieve database connection 
    db = getmongoservice("mymongodb").db("cf_local") 
    collection = db.students 
    fileToRead = "#ExpandPath('./test.cfc')#"; 
    jsonContent = FileRead(fileToRead); 
    serializedStr = serializeJSON(jsonContent); 
    collection.insertMany([{ 
        key: serializedStr, 
        name: "John Doe" 
    }]); 
    //Read from mongo 
    result = collection.find({"name" : {$eq:   "John Doe"}}).first() 
   
    fileDataFromMongo = structFind(result, "key"); 
    fileInJSON =  DeserializeJSON(fileDataFromMongo); 
</cfscript>

Serialize Array

<cfscript> 
    // Retrieve database connection 
    db = getmongoservice("mymongodb").db("cf_local") 
    collection = db.students 
    percentages =  [22.5 , 33 , 45]; 
    collection.insertMany([{ 
        name: "John Doe", 
 marks:{ 
     total: 15, 
     percentage : percentages 
 } 
   }]); 
    //Read from mongo 
    result = collection.find().first() 
    writedump(result) 
</cfscript>

Serialize BigDecimal

<cfscript> 
    // Retrieve database connection 
    db = getmongoservice("mymongodb").db("cf_local") 
    collection = db.students 
    percent = 3333333444222244.457777778900673 
    collection.insertMany([{ 
        name: "John Doe", 
 marks:{ 
     total: 15, 
     percent = 3333333444222244.457777778900673 
 } 
   }]); 
    //Read from mongo 
    result = collection.find({"name" : {$eq:   "John Doe"}}).first() 
    writedump(result) 
</cfscript>

Serialize PDF

<cfscript> 
    // Retrieve database connection 
    db = getmongoservice("mymongodb").db("cf_local") 
    collection = db.students 
     
    collection.insertMany([{ 
        name: "John Doe", 
 marks:{ 
     key: test, 
     name:"John Doe" 
 } 
   }]); 
    //Read from mongo 
    result = collection.find({"name" : {$eq:   "John Doe"}}).first() 
    writedump(result) 
    fileDataFromMongo = structFind(result, "key"); 
    myFile=GetDirectoryFromPath(GetCurrentTemplatePath()) & "test.pdf" 
    FileWrite(file=myFile, data= fileDataFromMongo) 
</cfscript> 
<cfpdf action="extracttext" pages = "1" source="#myFile#" name="myXML" />

Serialize Query

<cfscript> 
    // Retrieve database connection 
    db = getmongoservice("mymongodb").db("cf_local") 
    collection = db.students 
    myquery = QueryExecute('SELECT * FROM artists', [], {datasource = 'cfartgallery'}) 
    jsonqueryresult =  SerializeJSON(myquery) 
</cfscript> 
<cfset Start = 1> 
<cfset End = 1> 
<cfloop query="myquery" startRow = "#Start#" endRow = "#End#"> 
    <cfset address =    #myquery.ADDRESS#> 
</cfloop> 
<cfscript> 
    collection.insertMany([{ 
        key: myquery, 
        name: "John Doe", 
   }]); 
    //Read from mongo 
    result = collection.find({"name" : {$eq:   "John Doe"}}).first() 
    fileDataFromMongo = structFind(result, "key") 
</cfscript>

Serialize Image

<cfscript> 
    // Retrieve database connection 
    db = getmongoservice("mymongodb").db("cf_local") 
    collection = db.students 
    fileToRead = "#ExpandPath('./test1.png')#" 
    myfile = FileOpen(fileToRead, "readBinary"); 
    binaryFileContent = FileRead(myfile, 1000); 
    stringContentForBinaryFile = toString(binaryFileContent) 
     
    collection.insertMany([{ 
        key: binaryFileContent, 
        name: "John Doe" 
   }]); 
    //Read from mongo 
    result = collection.find({"name" : {$eq:   "John Doe"}}).first() 
    fileDataFromMongo = structFind(result, "key"); 
    fileInString = ToString(ToBinary(fileDataFromMongo)) 
</cfscript>

Serialize Spreadsheet

<cfscript>  
    theDir=GetDirectoryFromPath(GetCurrentTemplatePath());  
    theFile=theDir & "courses.xls";  
</cfscript> 
<cfspreadsheet action="read" src="#theFile#" sheetname="courses" name="spreadsheetData"> 
<cfscript> 
    // Retrieve database connection 
    db = getmongoservice("mymongodb").db("cf_local") 
    collection = db.students 
    data = spreadsheetData 
         
    collection.insertMany([{ 
        key: data, 
        name: "John Doe" 
   }]); 
    //Read from mongo 
    result = collection.find({"name" : {$eq:   "John Doe"}}).first() 
    MongoResultSheet = spreadsheetRead(result.key) 
    writedump(MongoResultSheet.ROWCOUNT) 
</cfscript>

Serialize XML

<cfscript> 
    // Retrieve database connection 
    db = getmongoservice("mymongodb").db("cf_local") 
    collection = db.students 
    myxml = fileRead(expandPath("./supportFiles/test.xml")); 
    mydoc = XmlParse(myxml) 
            
    collection.insertMany([{ 
        key: mydoc , 
        name: "John Doe" 
   }]); 
    //Read from mongo 
    result = collection.find({"name" : {$eq:   "John Doe"}}).first() 
    fileDataFromMongo = structFind(result, "key"); 
    fileInXML =  DeserializeXML(fileDataFromMongo) 
</cfscript>

Serialize RegEx

<cfscript> 
    // Retrieve database connection 
    db = getmongoservice("mymongodb").db("cf_local") 
    collection = db.students 
    percent = 44 
    collection.insertMany([{ 
       name: "John Doe", 
       marks:{ 
     total: 15, 
     percentage: 66-22 
        }  
   }]); 
    //Read from mongo 
    result = collection.find({"name" : {$eq:   "John Doe"}}).first() 
    if( result.marks.percentage eq percent){ 
           writeoutput("Pass"); 
    } 
</cfscript>

GetMongoBsonMinKey and GetMongoBsonMaxKey

<cfscript> 
    // Retrieve database connection 
    db = getmongoservice("mymongodb").db("cf_local") 
    collection = db.students 
    // Insert many documents 
    res = collection.insertMany([{ 
        enrollno: "110470116021", 
        name: "John Adams", 
        college: GetMongoBsonMinKey() 
    }, 
    { 
        enrollno: "110470116022", 
        name: "Jane Madison", 
        college: GetMongoBsonMaxKey() 
    }]) 
    res = collection.find().toArray() 
</cfscript>

Other data types

  • Date
  • BigInt
  • MongoObjectIdNew
  • MongoRegExpNew
  • MongoDBRefNew
  • MongoBsonJSNew
  • DataBaseReference

Database operations

Create a database

To create a db in MongoDB, use the service handler function getmongoservice and create the database.

<cfscript> 
       db = getmongoservice("mymongodb").db("mynewdb") // create a db  
       writeDump(db) 
</cfscript>

Create a collection

After you create a database, you must insert a collection in the database. To create a collection, you must create a MongoDB database object and create the collection inside the db. A db can consist of multiple collections.

<cfscript> 
       db = getmongoservice("mymongodb").db("mynewdb") // create a db 
       db.createCollection("mynewdbcollection") // create a collection called mynewdbcollection 
</cfscript>

Drop a database

<cfscript> 
       db = getmongoservice("mymongodb").db("mynewdb") // create a db 
       db.dropDatabase() // Removes the database 
</cfscript>

Get the name of a database

Use the getName method to retrieve the name of the database. For more information, see Get name of a database.

<cfscript> 
       db = getmongoservice("mymongodb").db("deeppurple") // create a db 
       db.createCollection("members") // create a collection 
       db.members.insertMany([ 
              
                    { "_id" : 1, "name" : "Ian Gillan", "instrument" : "Vocals","born": 1945 }, 
                    { "_id" : 2, "name" : "Ian Paice", "instrument" : "Drums", "born" : 1948 }, 
                    { "_id" : 3, "name" : "Roger Glover", "instrument" : "Bass", "born" : 1945 }, 
                    { "_id" : 4, "name" : "Steve Morse", "instrument" : "Guitar", "born" : 1954 }, 
                    { "_id" : 5, "name" : "Don Airey", "instrument" : "Keyboards", "born" : 1948 }, 
                    { "_id" : 6, "name" : "Jeff Martin", "instrument" : "Vocals", "born" : 1969 }, 
                    { "_id" : 7, "name" : "Jeff Burrows", "instrument" : "Drums", "born" : 1968 }, 
                    { "_id" : 8, "name" : "Stuart Chatwood", "instrument" : "Bass", "born" : 1969 } 
              
       ]) 
       get_name=db.members.getName() 
       writeOutput("The name of the database is: " & get_name) 
</cfscript>

Get the names of collections in a database

Use the getCollectionNames method to retrieve the names of all the collections in a database. For more information, see getCollectionNames docs. The output is an array of collection names.

<cfscript> 
       db = getmongoservice("mymongodb").db("rockband") // create a db 
       db.deeppurple.drop() 
       db.kingcrimson.drop() 
       db.createCollection("deeppurple") // create a collection 
       db.deeppurple.insertMany([ 
              
                    { "_id" : 1, "name" : "Ian Gillan", "instrument" : "Vocals","born": 1945 }, 
                    { "_id" : 2, "name" : "Ian Paice", "instrument" : "Drums", "born" : 1948 }, 
                    { "_id" : 3, "name" : "Roger Glover", "instrument" : "Bass", "born" : 1945 }, 
                    { "_id" : 4, "name" : "Steve Morse", "instrument" : "Guitar", "born" : 1954 }, 
                    { "_id" : 5, "name" : "Don Airey", "instrument" : "Keyboards", "born" : 1948 }, 
                    { "_id" : 6, "name" : "Jeff Martin", "instrument" : "Vocals", "born" : 1969 }, 
                    { "_id" : 7, "name" : "Jeff Burrows", "instrument" : "Drums", "born" : 1968 }, 
                    { "_id" : 8, "name" : "Stuart Chatwood", "instrument" : "Bass", "born" : 1969 } 
              
       ]) 
       db.createCollection("kingcrimson") // create another collection 
       db.kingcrimson.insertMany([ 
             {"_id":1,"name":"Robert Fripp","instrument":"Guitar", 
             "_id":2, "name": "Greg Lake","instrument":"Bass", 
             "_id":3, "name": "Ian McDonald","instrument":"Keyboard", 
             "_id":4, "name": "Michael Giles", "instrument":"Drums"} 
       ]) 
       collection_names=db.getCollectionNames() 
       writeDump(collection_names) 
</cfscript>

Get information about a collection

The getCollectionInfos method returns an array of documents with collection or view information, such as name and options, for the current database. For more information, see getCollectionInfos docs.

<cfscript> 
       // The following returns information for all collections in the rockband database 
       db = getmongoservice("mymongodb").db("rockband") 
       all_collections=db.getCollectionInfos() 
       writeDump(all_collections) 
</cfscript>

To request collection information for a specific collection, specify the collection name when calling the function.

<cfscript> 
       // The following returns information for all collections in the rockband database 
       db = getmongoservice("mymongodb").db("rockband") 
       out=db.getCollectionInfos({"born":1948}) 
       writeDump(out) 
</cfscript>

Collection- CRUD methods

db.collection.count

Counts the number of documents in a collection. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  // Members collection 
  countResponse=db.members.count() 
  writeDump(countResponse) // Returns all documents in the collection 
  // Count all documents that match a query 
  countResponse1=db.members.count( { born: { $gt: 1950 } } ) 
  writeDump(countResponse1) // Returns documents that match the criteria 
</cfscript>

db.collection.countdocuments

This function returns the count of documents that match the query for a collection.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  // Members collection 
  countResponse=db.members.countDocuments() 
  writeDump(countResponse) // Returns all documents in the collection 
  // Count all documents that match a query 
  countResponse1=db.members.countDocuments( { born: { $gt: 1950 } } ) 
  writeDump(countResponse1) // Returns documents that match the criteria 
</cfscript>

db.collection.estimatedDocumentCount

This function returns the count of documents in a collection or view.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  // Members collection 
  countResponse=db.members.countDocuments() 
  writeDump(countResponse) // Returns all documents in the collection 
  // Count all documents that match a query 
  countResponse1=db.members.estimatedDocumentCount( { born: { $gt: 1950 } } ) 
  writeDump(countResponse1) // Returns documents that match the criteria 
</cfscript>

db.collection.deleteOne

This function Removes a single document from a collection.

<cfscript> 
    // Retrieve database 
    db = getmongoservice("cosmos").db("mydb") 
    collection = db.collection 
    collection.drop() 
    writeOutput("number of documents in the collection: <b>" & collection.count() & " </b><br/>") 
    writeOutput("<b> Insert a document </b><br/>") 
    // Insert many documents 
    res = collection.insertMany([{ 
        enrollno: "1001", 
        name: "John Doe", 
        college: "Any college", 
        course: { 
            courseName: "Any course", 
            duration: "4 Years" 
        }, 
        address: { 
            city: "Any city", 
            state: "Any state", 
        country: "Any country" 
        } 
    }, 
    { 
    enrollno: "1002", 
    name: "Jane Doe", 
    college: "Some college", 
    course: { 
        courseName: "Some course", 
        duration: "4 Years" 
    }, 
    address: { 
        city: "Some city", 
        state: "Some state", 
        country: "Some country" 
    } 
    }]) 
    //count number of documents in the collection 
    writeOutput("number of documents in the collection: <b>" & collection.count() & " </b><br/>") 
    writeOutput("<b> Delete a document </b><br/>") 
    collection.deleteOne({name: MongoRegExp("John Doe","i")}) 
    writeOutput("number of documents in the collection: <b>" & collection.count() & " </b><br/>") 
</cfscript>

db.collection.deleteOne

This function removes all documents that match a filter condition from a collection.

<cfscript> 
   db = getmongoservice("mongodb").db("imdb"); 
   db.orders.drop() 
   db.orders.insertOne({ 
   _id: MongoObjectId("563237a41a4d68582c2509da"), 
   stock: "Brent Crude Futures", 
   qty: 250, 
   type: "buy-limit", 
   limit: 48.90, 
   creationts: ParseDateTime("2015-11-01T12:30:15Z"), 
   expiryts: ParseDateTime("2015-11-01T12:35:15Z"), 
   client: "Crude Traders Inc." 
   }) 
   writeoutput("count: " & db.orders.count() & " <br/>"); 
   res = db.orders.deleteMany( { "client" : "Crude Traders Inc." } ); 
   writedump(Res) 
   writeoutput("count: " & db.orders.count() & " <br/>"); 
   res = db.orders.deleteMany( { "stock" : "Brent Crude Futures", "limit" : { $gt : 48.88 } } ); 
   writedump(Res) 
   res = db.orders.deleteMany( 
   { "client" : "Crude Traders Inc." }, 
   { w : "majority", wtimeout : 100 } 
   ); 
   writedump(Res) 
   writeoutput("collation example") 
   db.mycoll.drop(); 
   res = db.mycoll.insert([{ _id: 1, category: "café", status: "A" }, 
   { _id: 2, category: "cafe", status: "a" }, 
   { _id: 3, category: "cafE", status: "a" }]) 
   writedump(res) 
   res = db.myColl.deleteMany( 
   { category: "cafe", status: "A" }, 
   { collation: { locale: "fr", strength: 1 } } 
   ) 
   writedump(res) 
   db.myColl.find().foreach((s) => { 
   writedump(s) 
   }) 
   db.mycoll.drop(); 
   db.orders.drop() 
</cfscript>

db.collection.distinct

This function finds distinct values for a specified field in a single collection.

<cfscript> 
    db = getmongoservice("mymongodb").db("imdb"); 
 
    res = db.myColl1.insertMany([ 
        { _id: 1, category: "café", status: 01 }, 
        { _id: 2, category: "cafe", status: 02 }, 
        { _id: 3, category: "cafE", status: 03 } 
    ]) 
    res = db.myColl1.distinct( "category", {}, { collation: { locale: "fr", strength: 1 } } ) 
    writedump(res) 
</cfscript>

db.collection.drop

This function removes a collection from a database.

<cfscript> 
 db = getmongoservice("mymongodb").db("mynewdb") // create a db 
 db.createCollection("mynewdbcollection") // create a collection called mynewdbcollection 
  
 try { 
  db.mynewdbcollection.drop() // Removes the collection 
  writeOutput("Collection removed sucessfully.") 
 } 
  
 catch (any e){ 
  writeOutput("Unable to remove collection.") 
 } 
 // 
</cfscript>

db.collection.explain

This function returns information for the mthods listed in this doc.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  // Members collection 
  // Count function 
  explainResponse1=db.members.explain().count({ 
    born:{$gt:1950} 
  }) 
  writeDump(explainResponse1) 
</cfscript>

db.collection.find

This function selects documents in a collection or view. For more information, see db.collection.fine.

<cfscript> 
 db = getmongoservice("mymongodb").db("newdb") // create a db 
 //db.colFindDemo.drop() 
 db.createCollection("colFindDemo") // create a collection 
 db.colFindDemo.insertMany([ 
   
   { "_id" : 1, "name" : "Ian Gillan", "instrument" : "Vocals","born": 1945 }, 
   { "_id" : 2, "name" : "Ian Paice", "instrument" : "Drums", "born" : 1948 }, 
   { "_id" : 3, "name" : "Roger Glover", "instrument" : "Bass", "born" : 1945 }, 
   { "_id" : 4, "name" : "Steve Morse", "instrument" : "Guitar", "born" : 1954 }, 
   { "_id" : 5, "name" : "Don Airey", "instrument" : "Keyboards", "born" : 1948 }, 
   { "_id" : 6, "name" : "Jeff Martin", "instrument" : "Vocals", "born" : 1969 }, 
   { "_id" : 7, "name" : "Jeff Burrows", "instrument" : "Drums", "born" : 1968 }, 
   { "_id" : 8, "name" : "Stuart Chatwood", "instrument" : "Bass", "born" : 1969 } 
   
 ]) 
 // return all documents 
 db.colFindDemo.find() 
 writedump(res) 
</cfscript>

Other snippets-

<cfscript> 
 db.colFindDemo.find({"_id":4}) 
</cfscript> 
 
<cfscript> 
 db.colFindDemo.find({"instrument":"Drums"}) 
</cfscript> 
 
<cfscript> 
 df.colFindDemo.find({"_id":{$gt:4}}) // find _ids greater than 4 
</cfscript> 
 
<cfscript> 
 df.colFindDemo.find({"instrument":{$regex:"^B"}}) // find instruments that start with B 
</cfscript> 
 
<cfscript> 
 db.colFindDemo.find({"name":{$in:["Ian Gillan","Ian Paice"]}}) // find documents that match the names 
</cfscript> 
 
<cfscript> 
 db.colFindDemo.find({"born":{$all:[1948]}}) // find documents that match born, which contains the year 1948 
</cfscript> 
 
<cfscript> 
 // find all documents where instrument is Drums or the year of birth is 1948 
 db.colFindDemo.find({$or:[{"instrument":"Drums"},{"born":1948}]}) 
</cfscript>

db.collection.insert

This function inserts a document or documents into a collection.

<cfscript> 
 db = getmongoservice("mymongodb").db("newdb") // create a db 
 db.createCollection("newcolThree") // create a collection 
 // insert a single document 
 db.newcolThree.insert({ 
  "_id": 1, 
  "name":"John Lennon", 
  "band":"Beatles" 
 }) 
</cfscript> 

db.collection.insertOne

This function inserts a single document into a collection.

<cfscript> 
 db = getmongoservice("mymongodb").db("newdb") // create a db 
 db.newcolThree.drop() // drop the collection 
 db.createCollection("newcolThree") // create a collection 
 // insert a single document 
 db.newcolThree.insert({ 
  "_id": 1, 
  "name":"John Lennon", 
  "band":"Beatles" 
 }) 
 // insert another document 
 db.newcolThree.insertOne({ 
  "_id": 2, 
  "name":"Paul McCartney", 
  "band":"Beatles" 
 }) 
 // insert many documents 
 db.newcolThree.insertMany([ 
  { 
   "_id": 3, 
   "name":"George Harrison", 
   "band":"Beatles" 
  }, 
  { 
   "_id": 4, 
   "name":"Ringo Starr", 
   "band":"Beatles" 
  } 
 ]) 
</cfscript>

db.collection.insertMany

This function inserts multiple documents into a collection.

<cfscript> 
 db = getmongoservice("mymongodb").db("newdb") // create a db 
 db.newcolThree.drop() // drop the collection 
 db.createCollection("newcolThree") // create a collection 
 // insert a single document 
 db.newcolThree.insert({ 
  "_id": 1, 
  "name":"John Lennon", 
  "band":"Beatles" 
 }) 
 // insert another document 
 db.newcolThree.insertOne({ 
  "_id": 2, 
  "name":"Paul McCartney", 
  "band":"Beatles" 
 }) 
 // insert many documents 
 db.newcolThree.insertMany([ 
  { 
   "_id": 3, 
   "name":"George Harrison", 
   "band":"Beatles" 
  }, 
  { 
   "_id": 4, 
   "name":"Ringo Starr", 
   "band":"Beatles" 
  } 
 ]) 
</cfscript>

db.collection.isCapped

This function checks if a collection is a capped collection.

<cfscript> 
    db = getmongoservice("mymongodb").db("newdb") // create a db 
    ifCapped=db.cappedLogCollection.isCapped() 
    writeOutput("Is collection capped: "& ifCapped) 
</cfscript>

db.collection.latencyStats

This function returns the latency statistics of a collection. For more information, see db.collection.latencyStats.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  // Members collection 
  latencyStatsResponse=db.members.latencyStats( { histograms: true } ) 
  writedump(latencyStatsResponse) 
</cfscript>

db.collection.remove

This function removes documents from a collection.

<cfscript> 
    db = getmongoservice("mymongodb").db("db_source") // create a db 
    db.createCollection("mycolone") // create a collection 
    // insert a single document 
    db.mycolone.insert({ 
        "_id": 1, 
        "name":"John Lennon", 
        "band":"Beatles" 
    }) 
    // insert another document 
    db.mycolone.insertOne({ 
        "_id": 2, 
        "name":"Paul McCartney", 
        "band":"Beatles" 
    }) 
    // insert many documents 
    db.mycolone.insertMany([ 
        { 
            "_id": 3, 
            "name":"George Harrison", 
            "band":"Beatles" 
        }, 
        { 
            "_id": 4, 
            "name":"Ringo Starr", 
            "band":"Beatles" 
        } 
    ]) 
    // remove a document 
    try{ 
        db.mycolone.remove({}) 
        writeOutput("Document removed sucessfully") 
    } 
    catch ( any e) { 
        writeDump(e) 
    } 
</cfscript>

db.collection.renameCollection

This function renames a collection.

<cfscript> 
    db = getmongoservice("mymongodb").db("db_source") // create a db 
    // create a collection 
    db.createCollection("coll_old") 
    renameRes=db.coll_old.renameCollection("coll_new") 
    writeDump(renameRes) 
</cfscript>

db.collection.replaceOne

This function replaces a single document in the collection based on a filter.

<cfscript> 
   db = getmongoservice("mongodb").db("imdb"); 
   //db.restaurant.drop() 
 
   res = db.restaurant.insertMany([ 
      { "_id" : 1, "name" : "Central Perk Cafe", "Borough" : "Manhattan" }, 
      { "_id" : 2, "name" : "Rock A Feller Bar and Grill", "Borough" : "Queens", "violations" : 2 }, 
      { "_id" : 3, "name" : "Empire State Pub", "Borough" : "Brooklyn", "violations" : 0 }]) 
 
   // writedump(res) 
 
   db.restaurant.find().foreach((s) => { 
    writedump(s) 
   }) 
 
   res = db.restaurant.replaceOne( 
      { "name" : "Central Perk Cafe" }, 
      { "name" : "Central Pork Cafe", "Borough" : "Manhattan", "violations": 10 } 
   ) 
   writedump(res) 
</cfscript>

db.collection.stats

This function returns statistics of a collection. For more information, see db.collection.stats.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  statsResponse=db.articles.stats()  
  writeDump(statsResponse) 
</cfscript>

db.collection.storageSize

This function returns the size of the storage of a document in a collection.

<cfscript> 
    db = getmongoservice("mymongodb").db("imdb"); 
    db.log.drop() 
    col = db.createCollection("log", { capped : true, size : 5242880, max : 3 } ).count(); 
    //writedump(col); 
 
    res = db.log.insertMany([ 
        { _id: 1, category: "café", status: 01 }, 
        { _id: 2, category: "cafe", status: 02 }, 
        { _id: 3, category: "cafE", status: 03 } 
    ]) 
    //writedump(res); 
    writedump(db.log.storageSize()) 
</cfscript>

db.collection.storageSize

This function returns the total size in bytes of the data in the collection.

<cfscript> 
    db = getmongoservice("mymongodb").db("imdb"); 
    db.log.drop() 
    col = db.createCollection("log", { capped : true, size : 5242880, max : 3 } ).count(); 
    //writedump(col); 
    res = db.log.insertMany([ 
        { _id: 1, category: "café", status: 01 }, 
        { _id: 2, category: "cafe", status: 02 }, 
        { _id: 3, category: "cafE", status: 03 } 
    ]) 
    //writedump(res); 
    writedump(db.log.totalSize()) 
</cfscript>

db.collection.update

This function modifies a document or documents in a collection.

<cfscript> 
    db = getmongoservice("mymongodb").db("newdb") // create a db 
    db.colUpdDemo.drop() 
    db.createCollection("colUpdDemo") // create a collection 
    db.colUpdDemo.insertMany([ 
        { 
          "_id":1, 
          "product_name": "sildenafil citrate", 
          "supplier": "Wisozk Inc", 
          "quantity": 261, 
          "unit_cost": "$10.47" 
        }, 
        { 
          "_id":2, 
          "product_name": "Mountain Juniperus ashei", 
          "supplier": "Keebler-Hilpert", 
          "quantity": 292, 
          "unit_cost": "$8.74" 
        }, 
        { 
          "_id":3, 
          "product_name": "Dextromathorphan HBr", 
          "supplier": "Schmitt-Weissnat", 
          "quantity": 211, 
          "unit_cost": "$20.53" 
        } 
]) 
    // increment quantity by 10 for _id:1 
    db.colUpdDemo.update({"_id":1},{$inc:{"quantity":10}}) 
    // update unit cost from 8.74 to 10.74 
    db.colUpdDemo.update({"_id":2},{$set:{"unit_cost": "$10.74"}}) 
</cfscript>

db.collection.updateOne

This function modifies a single document in a collection based on a filter.

<cfscript> 
    db = getmongoservice("mymongodb").db("newdb") // create a db 
    db.colUpdDemo.drop() 
    db.createCollection("colUpdDemo") // create a collection 
    db.colUpdDemo.insertMany([ 
        { 
          "_id":1, 
          "product_name": "sildenafil citrate", 
          "supplier": "Wisozk Inc", 
          "quantity": 261, 
          "unit_cost": "$10.47", 
          "stock":10000 
        }, 
        { 
          "_id":2, 
          "product_name": "Mountain Juniperus ashei", 
          "supplier": "Keebler-Hilpert", 
          "quantity": 292, 
          "unit_cost": "$8.74", 
          "stock":15000 
        }, 
        { 
          "_id":3, 
          "product_name": "Dextromathorphan HBr", 
          "supplier": "Schmitt-Weissnat", 
          "quantity": 211, 
          "unit_cost": "$20.53", 
          "stock":20000 
        } 
]) 
    db.colUpdDemo.updateOne({"supplier": "Keebler-Hilpert"},{$set:{"stock":16000}}) 
</cfscript>

db.collection.updateMany

This function modifies all documents in a collection based on a filter.

<cfscript> 
       db = getmongoservice("mymongodb").db("newdb") // create a db 
       db.colUpdManyDemo.drop() 
       db.createCollection("colUpdManyDemo") // create a collection 
       db.colUpdManyDemo.insertMany([ 
             { 
             "_id":1, 
             "product_name": "sildenafil citrate", 
             "supplier": "Wisozk Inc", 
             "quantity": 261, 
             "unit_cost": "$10.47", 
             "stock":10000 
             },  
             { 
             "_id":2, 
             "product_name": "Mountain Juniperus ashei", 
             "supplier": "Keebler-Hilpert", 
             "quantity": 292, 
             "unit_cost": "$8.74", 
             "stock":15000 
             },  
             { 
             "_id":3, 
             "product_name": "Dextromathorphan HBr", 
             "supplier": "Schmitt-Weissnat", 
             "quantity": 211, 
             "unit_cost": "$20.53", 
             "stock":20000 
             } 
       ]) 
       // update more than one document based on the specified filter 
       db.colUpdManyDemo.updateMany( {"quantity" : {$gt: 250 }}, {$set: { "stock" : 50000 } } ); 
</cfscript>

db.collection.validate

This function scans a collection and decides if the collection is a valid one.

<cfscript> 
    db = getmongoservice("mymongodb").db("newdb") // create a db 
    db.colUpdManyDemo.drop() 
    db.createCollection("colUpdManyDemo") // create a collection 
    db.colUpdManyDemo.insertMany([ 
          { 
          "_id":1, 
          "product_name": "sildenafil citrate", 
          "supplier": "Wisozk Inc", 
          "quantity": 261, 
          "unit_cost": "$10.47", 
          "stock":10000 
          },  
          { 
          "_id":2, 
          "product_name": "Mountain Juniperus ashei", 
          "supplier": "Keebler-Hilpert", 
          "quantity": 292, 
          "unit_cost": "$8.74", 
          "stock":15000 
          },  
          { 
          "_id":3, 
          "product_name": "Dextromathorphan HBr", 
          "supplier": "Schmitt-Weissnat", 
          "quantity": 211, 
          "unit_cost": "$20.53", 
          "stock":20000 
          } 
    ]) 
    // update more than one document based on the specified filter 
    db.colUpdManyDemo.updateMany( {"quantity" : {$gt: 250 }}, {$set: { "stock" : 50000 } } ); 
    isValidate=db.colUpdManyDemo.validate() 
    writeDump(isValidate) 
</cfscript>

Collection- Advanced methods

db.collection.bulkWrite

This function performs multiple write operations enabling you to define the order of execution.

<cfscript> 
   // Retrieve database  
   db = getmongoservice("mymongodb").db("imdb") 
   db.characters.drop() 
   db.characters.insert([ 
      { "_id" : 1, "char" : "Brisbane", "class" : "monk", "lvl" : 4 }, 
      { "_id" : 2, "char" : "Eldon", "class" : "alchemist", "lvl" : 3 }, 
      { "_id" : 3, "char" : "Meldane", "class" : "ranger", "lvl" : 3 } 
      ]) 
 
   res = db.characters.bulkWrite([ 
      { insertOne: { "document": { "_id": 4, "char": "Dithras", "class": "barbarian", "lvl": 4 } } }, 
      { insertOne: { "document": { "_id": 5, "char": "Taeln", "class": "fighter", "lvl": 3 } } }, 
      { updateOne : { 
         "filter" : { "char" : "Eldon" }, 
         "update" : { $set : { "status" : "Critical Injury" } } 
      } }, 
      { deleteOne : { "filter" : { "char" : "Brisbane"} } }, 
      { replaceOne : { 
         "filter" : { "char" : "Meldane" }, 
         "replacement" : { "char" : "Tanys", "class" : "oracle", "lvl": 4 } 
      } } 
   ]) 
   writedump(res) 
</cfscript>

db.collection.findAndModify

This function modifies and returns a single document. For more information, see db.collection.findandmodify.

<cfscript> 
    db = getmongoservice("mymongodb").db("student_db") 
    db.students.drop() 
    // create a collection 
    db.createCollection("students") 
    // Insert many documents 
    // Insert many documents 
    db.students.insertMany([ 
    { 
        enrollno: "1001", 
        name: "John Doe", 
        college: "Amherst", 
        course: { 
            courseName: "Math", 
            duration: "4 Years" 
        }, 
        address: { 
            city: "Any city", 
            state: "Any state", 
            country: "USA" 
        } 
    }, 
    { 
        enrollno: "1002", 
        name: "Jane Doe", 
        college: "Vassar", 
        course: { 
            courseName: "Physics", 
            duration: "4 Years" 
        }, 
        address: { 
            city: "Some city", 
            state: "Some state", 
            country: "USA" 
        } 
    }]) 
    try{ 
        res = db.students.findAndModify({ $and : [{ "enrollno" : {$gt : "1002"}} , {"name" : {$eq:"Jane Smith"}}]}) 
        writeDump(res) 
        writeOutput("Record modified successfully") 
    } 
    catch(any e){ 
        writeDump(e) 
    } 
</cfscript>

db.collection.findOne

This function returns a single document based on a filter. For more information, see db.collection.findone.

<cfscript> 
    db = getmongoservice("mymongodb").db("newdb") // create a db 
 //db.music.drop() 
 db.createCollection("music") // create a collection 
 db.music.insertMany([ 
   
   { "_id" : 1, "name" : "Ian Gillan", "instrument" : "Vocals","born": 1945 }, 
   { "_id" : 2, "name" : "Ian Paice", "instrument" : "Drums", "born" : 1948 }, 
   { "_id" : 3, "name" : "Roger Glover", "instrument" : "Bass", "born" : 1945 }, 
   { "_id" : 4, "name" : "Steve Morse", "instrument" : "Guitar", "born" : 1954 }, 
   { "_id" : 5, "name" : "Don Airey", "instrument" : "Keyboards", "born" : 1948 }, 
   { "_id" : 6, "name" : "Jeff Martin", "instrument" : "Vocals", "born" : 1969 }, 
   { "_id" : 7, "name" : "Jeff Burrows", "instrument" : "Drums", "born" : 1968 }, 
   { "_id" : 8, "name" : "Stuart Chatwood", "instrument" : "Bass", "born" : 1969 } 
   
    ]) 
    try{ 
        res = db.music.findOne( {"name" : {$eq:"Ian Gillan"}}) 
        writeDump(res) 
        writeOutput("Record returned successfully") 
    } 
    catch(any e){ 
        writeDump(e) 
    } 
</cfscript>

db.collection.findOneAndDelete

This function deletes a single document based on a filter. For more information, see db.collection.findoneanddelete.

<cfscript> 
    db = getmongoservice("mymongodb").db("student_db") 
    db.students.drop() 
    // create a collection 
    db.createCollection("students") 
    // Insert many documents 
     
    db.students.insertMany([ 
    { 
        enrollno: "1001", 
        name: "John Doe", 
        college: "Amherst", 
        course: { 
            courseName: "Math", 
            duration: "4 Years" 
        }, 
        address: { 
            city: "Any city", 
            state: "Any state", 
            country: "USA" 
        } 
    }, 
    { 
        enrollno: "1002", 
        name: "Jane Doe", 
        college: "Vassar", 
        course: { 
            courseName: "Physics", 
            duration: "4 Years" 
        }, 
        address: { 
            city: "Some city", 
            state: "Some state", 
            country: "USA" 
        } 
    }]) 
    try{ 
        res = db.students.findOneAndDelete({ $and : [{ "enrollno" : {$gt : "1000"}} , {"name" : {$eq:"Jane Doe"}}]}) 
        writeDump(res) 
        writeOutput("Record deleted successfully") 
    } 
    catch(any e){ 
        writeDump(e) 
    } 
</cfscript>

db.collection.findOneAndReplace

This function replaces a single document based on a filter. For more information, see db.collection.findoneandreplace.

<cfscript> 
    db = getmongoservice("mymongodb").db("newdb") 
    //db.team.drop() 
    // create a collection 
    db.createCollection("team") 
    // Insert many documents 
    db.team.insertMany([ 
        { "_id" : 1521, "team" : "Fearful Mallards", "score" : 25000 }, 
        { "_id" : 2231, "team" : "Tactful Mooses", "score" : 23500 }, 
        { "_id" : 4511, "team" : "Aquatic Ponies", "score" : 19250 }, 
        { "_id" : 5331, "team" : "Cuddly Zebras", "score" : 15235 }, 
        { "_id" : 3412, "team" : "Garrulous Bears", "score" : 22300 } 
    ]) 
    try{ 
        res = db.team.findOneAndReplace( 
                { "score" : { $lt : 30000 } }, 
                { "team" : "Observant Badgers", "score" : 20000 , "owner" : "disney"}, 
                { sort : { "score" : -1 }, projection: { "_id" : 0, "team" : 1 } } 
        ) 
        writeOutput("Record returned successfully") 
        writeDump(res) 
    } 
    catch (any e) { 
        writeDump(e) 
    } 
</cfscript>

db.collection.findOneAndUpdate

This function updates a single document based on a filter. For more information, see db.collection.findoneandupdate.

<cfscript> 
    db = getmongoservice("mymongodb").db("newdb") 
    //db.grades.drop() 
 
    db.createCollection("grades") 
  
    // Insert many documents 
    db.grades.insertMany([ 
        { _id: 6305, name : "A. MacDyver", "assignment" : 5, "points" : 24 }, 
        { _id: 6308, name : "B. Batlock", "assignment" : 3, "points" : 22 }, 
        { _id: 6312, name : "M. Tagnum", "assignment" : 5, "points" : 30 }, 
        { _id: 6319, name : "R. Stiles", "assignment" : 2, "points" : 12 }, 
        { _id: 6322, name : "A. MacDyver", "assignment" : 2, "points" : 14 }, 
        { _id: 6234, name : "R. Stiles", "assignment" : 1, "points" : 10 } 
    ]) 
 
    // with find records - records exists , use options  
    try{ 
        res = db.grades.findOneAndUpdate( 
                { "name" : "A. MacDyver" }, 
                { $inc : { "points" : 5 } }, 
                { sort : { "points" : 1 }, projection: { "assignment" : 1, "points" : 1 } } 
        ) 
        writeOutput("Record updated successfully") 
    } 
    catch(any e){ 
        writeDump(e) 
    } 
</cfscript>

Aggregate methods

db.collection.aggregate

This function aggregates values for data in a collection. For more information, see db.collection.aggregate.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  db.scores.drop() 
  // create a collection 
  db.createCollection("scores") 
  db.scores.insertMany([ 
  { 
      _id: 1, 
      student: "Maya", 
      homework: [ 10, 5, 10 ], 
      quiz: [ 10, 8 ], 
      extraCredit: 0 
  }, 
  { 
    _id: 2, 
    student: "Ryan", 
    homework: [ 5, 6, 5 ], 
    quiz: [ 8, 8 ], 
    extraCredit: 8 
 } 
 ]) 
 addFieldsResponse=db.scores.aggregate( [ 
   { 
     $addFields: { 
       totalHomework: { $sum: "$homework" } , 
       totalQuiz: { $sum: "$quiz" } 
     } 
   }, 
   { 
     $addFields: { totalScore: 
       { $add: [ "$totalHomework", "$totalQuiz", "$extraCredit" ] } } 
   } 
] ) 
 writeDump(addFieldsResponse) 
</cfscript>

db.collection.distinct

This function returns the distinct values in a collection. For more information, see the official docs.

<cfscript> 
    db = mongoservice("mymongodb").db("db_source") // create a db 
    // Members collection 
    distinctResponse=db.members.distinct("instrument") 
    writeDump(distinctResponse) 
</cfscript>

db.collection.count

Counts the number of documents in a collection. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  // Members collection 
  countResponse=db.members.count() 
  writeDump(countResponse) // Returns all documents in the collection 
  // Count all documents that match a query 
  countResponse1=db.members.count( { born: { $gt: 1950 } } ) 
  writeDump(countResponse1) // Returns documents that match the criteria 
</cfscript>

db.collection.mapReduce

This function acts as a wrapper for mapReduce function. For more information, see the official docs.

<cfscript> 
    try 
    { 
        db = getmongoservice("mymongodb").db("mrd") 
        collection_orders = db.collection("orders") 
        //writedump(collection_orders); 
        collection_orders.insertmany([ 
        { 
            _id: CreateUUID(), 
            cust_id: "abc123", 
            ord_date:DateFormat("Oct 04, 2012"), 
            status: 'A', 
            price: 25, 
            items: [  
                { sku: "mmm", qty: 5, price: 2.5 }, 
                { sku: "nnn", qty: 5, price: 2.5 } ] 
        }, 
        { 
            _id: CreateUUID(), 
            cust_id: "def123", 
            ord_date:DateFormat("Oct 04, 2012"), 
            status: 'A', 
            price: 25, 
            items: [  
                { sku: "mmm", qty: 5, price: 2.5 }, 
                { sku: "nnn", qty: 5, price: 2.5 } ] 
        } 
    ]) 
    mapFunction1 = function() { 
            emit(this.cust_id, this.price); 
    } 
    reduceFunction1 = function(keyCustId, valuesPrices){ 
            return Array.sum(valuesPrices); 
    } 
    res = collection_orders.mapReduce( 
            "#mapFunction1#", 
            "#reduceFunction1#", 
            { out: "sample_output"}) 
    writeoutput("No of records fetched after map-reduce:" & res.len()); 
    writeoutput("<br>Value returned from records:" & res[1].value & "," & res[2].value) 
    } 
    catch(any e){ 
        writedump(e) 
    } 
    finally{ 
        db.orders.drop(); 
        db.runCommand({dropDatabase:1}); 
    } 
</cfscript>

Stream method

In MongoDB, streams enable applications to stream real-time data changes by using MongoDB’s replication capabilities. Streams help in updating data in real time so that applications access the most recent data. For example, trading systems, IOT data use data streams extensively.

Change streams notify your application of all writes to documents and provide access to information as and when changes occur, without any polling of data.

Collections.watch

This function opens a change stream for a collection. For more information, see db.collection.watch.

<cfscript> 
    // Retrieve database 
    db = getmongoservice("sharded").db("streamtest"); 
    res = db.adminCommand( { 
        enableSharding: "streamtest" 
    } ) 
    collection = db.Students; 
    res = db.adminCommand( { shardCollection: "streamtest.Students", key: { enrollno: 1 } } ); 
    cursor = collection.watch(); 
    // Insert many documents 
    res = collection.insertMany([{ 
        enrollno: "1001", 
        name: "John Doe", 
        college: "Amherst", 
        course: { 
            courseName: "Math", 
            duration: "4 Years" 
        }, 
        address: { 
            city: "Any city", 
            state: "Any state", 
            country: "USA" 
        } 
    }]) 
    streamRes = cursor.Next(); 
    writedump(var=streamRes , label="Cursor.next"); 
</cfscript>

Query caching

You can implement caching in MongoDB with the help of the following:

CachedAfter: You can cache a MongoDB query using the cachedAfter attribute. If the query was last run after the supplied date, cached data is used. Otherwise the query is re-run.

CachedWithin: The cachedWithin attribute instructs ColdFusion to execute a MongoDB query ONLY if it does not have a result set from that exact query in memory already.

CachedAfter

<cfscript> 
    db = getmongoservice("mymongodb").db("db_cache") // create a db 
    collection = db.students 
    // Insert many documents 
    collection.insertMany([ 
    { 
        enrollno: "1001", 
        name: "John Doe", 
        college: "Amherst", 
        course: { 
            courseName: "Math", 
            duration: "4 Years" 
        }, 
        address: { 
            city: "Any city", 
            state: "Any state", 
            country: "USA" 
        } 
    }, 
    { 
        enrollno: "1002", 
        name: "Jane Doe", 
        college: "Vassar", 
        course: { 
            courseName: "Physics", 
            duration: "4 Years" 
        }, 
        address: { 
            city: "Some city", 
            state: "Some state", 
            country: "USA" 
        } 
    }]) 
    currentDate = now(); 
    res1 = collection.find({ $and : [{ "enrollno" : {$gt : "1000"}} , {"name" : {$eq: "John Doe"}}]}).cachedAfter(DateAdd("s",3,currentDate)).toArray(); 
    writeOutput("<br/>Reading from db... Count is " & ArrayLen(res1)); 
    collection.insertMany([{ 
        enrollno: "1001", 
        name: "John Doe", 
        college: "Amherst", 
        course: { 
            courseName: "Math", 
            duration: "4 Years" 
        }, 
        address: { 
            city: "Any city", 
            state: "Any state", 
            country: "USA" 
        } 
    }]) 
    sleep(1000); 
    res = collection.find({ $and : [{ "enrollno" : {$gt : "1000"}} , {"name" : {$eq: "John Doe"}}]}).cachedAfter(DateAdd("s",3,currentDate)).toArray(); 
    writeOutput("<br/>reading from db before cacheAfter time... Count is " & ArrayLen(res)); 
</cfscript>

CachedWithin

<cfscript> 
    db = getmongoservice("mymongodb").db("db_cache") // create a db 
    collection = db.students 
    // Insert many documents 
    collection.insertMany([ 
    { 
        enrollno: "1001", 
        name: "John Doe", 
        college: "Amherst", 
        course: { 
            courseName: "Math", 
            duration: "4 Years" 
        }, 
        address: { 
            city: "Any city", 
            state: "Any state", 
            country: "USA" 
        } 
    }, 
    { 
        enrollno: "1002", 
        name: "Jane Doe", 
        college: "Vassar", 
        course: { 
            courseName: "Physics", 
            duration: "4 Years" 
        }, 
        address: { 
            city: "Some city", 
            state: "Some state", 
            country: "USA" 
        } 
    }]) 
    currentDate = now(); 
    res1 = collection.find({ $and : [{ "enrollno" : {$gt : "1000"}} , {"name" : {$eq: "John Doe"}}]}).cachedAfter(DateAdd("s",3,currentDate)).toArray(); 
    writeOutput("<br/>Reading from db... Count is " & ArrayLen(res1)); 
    collection.insertMany([{ 
        enrollno: "1001", 
        name: "John Doe", 
        college: "Amherst", 
        course: { 
            courseName: "Math", 
            duration: "4 Years" 
        }, 
        address: { 
            city: "Any city", 
            state: "Any state", 
            country: "USA" 
        } 
    }]) 
    sleep(1000) 
    res = collection.find({ $and : [{ "enrollno" : {$gt : "1000"}} , {"name" : {$eq: "John Doe"}}]}).cachedWithin(createTimespan(0, 0, 0, 5)).toArray(); 
    writeOutput("<br/>reading from cache... Count is " & ArrayLen(res)); 
</cfscript>

GRIDFS methods

GridFS stores files in chunks, instead of storing a file in a single document. Each chunk is stored as a separate document. For more information, see GridFS.

Instead of storing a file in a single document, GridFS divides the file into parts, or chunks [1], and stores each chunk as a separate document.

db.createBucket

GridFS stores collections in a bucket. This function creates indexes on a collection. 

<cfscript> 
    db=getmongoservice("mymongodb").db("newdb") 
    try{ 
        res=db.createBucket("newbucket") // create bucket 
        writeOutput("Bucket created successfully") 
        writeDump(res) 
    } 
    catch(any e){ 
        writeDump(e) 
    } 
    finally{ 
        res.drop() 
    } 
</cfscript>

bucket.upload

Upload a file in a bucket.

<cfscript> 
    bucket = getmongoservice("mymongodb").db("newdb").createbucket("bucket3"); 
     
    try{ 
        returnId = bucket.upload(expandPath(".") & "/exception.log") 
        writeOutput("File uploaded successfully") 
        writeDump(returnId) 
    } 
    catch(any e){ 
        writeDump(e) 
    } 
</cfscript>

bucket.download

Download a file from a bucket.

<cfscript> 
    bucket = getmongoservice("mymongodb").db("newdb").createbucket("bucket"); 
    // upload a file 
    returnId = bucket.upload(expandPath(".") & "/exception.log") 
    try{ 
        result = bucket.download(expandPath("."), mongoObjectId(returnId)) 
        writeOutput("File downloaded successfully") 
        writeDump(result) 
    } 
    catch(any e){ 
        writeDump(e) 
    } 
</cfscript>

bucket.rename

Renames a file in a bucket.

<cfscript> 
    bucket = getmongoservice("mymongodb").db("newdb").createbucket("bucket") 
    // upload a file 
    returnId = bucket.upload(expandPath(".") & "/exception.log") 
    // rename the file in the bucket 
    try{ 
        bucket.rename(returnId, "exceptionNew.log") 
        writeOutput("File renamed successfully") 
    } 
    catch(any e){ 
        writeDump(e) 
    } 
</cfscript>

bucket.find

Searches for a file in a bucket.

<cfscript> 
    bucket = getmongoservice("mymongodb").db("newdb").createbucket("bucket") 
    // upload a file 
    returnId = bucket.upload(expandPath(".") & "/exception.log") 
    // rename the file in the bucket 
    bucket.rename(returnId, "exceptionNew.log") 
    try{ 
        res = bucket.find({filename: "exceptionNew.log"}).toArray() // find the file 
        if(res[1].filename == "exceptionNew.log") 
        {  
            writeoutput("File has been found.") 
        } 
    } 
    catch(any e){ 
        writeDump(e) 
    } 
</cfscript>

bucket.delete

Deletes a file in a bucket.

<cfscript> 
    bucket = getmongoservice("mymongodb").db("newdb").createbucket("bucket") 
    // upload a file 
    returnId = bucket.upload(expandPath(".") & "/exception.log") 
    try{ 
        res = bucket.delete(returnId) 
        if(res.name == "bucket"){ 
            writeoutput("File deleted successfully") 
        } 
    } 
    catch (any e){ 
        writeDump(e) 
    } 
</cfscript>

bucket.drop

Deletes a bucket.

<cfscript> 
    bucket = getmongoservice("mymongodb").db("newdb").createbucket("bucket") 
    try{ 
        res = bucket.drop() 
        if(res.name == "bucket"){ 
            writeoutput("Bucket is deleted successfully") 
        } 
    } 
    catch(any e){ 
        writeDump(e) 
    } 
</cfscript>

Index methods

db.collection.createIndex

This function creates indexes on a collection. For more information, see the official docs.

<cfscript> 
 db = getmongoservice("mymongodb").db("imdb"); 
 //db.products.drop() 
 db.createCollection("products") 
 // insert documents 
 db.products.insertMany([ 
     { "_id" : 1, "item" : "apple", "type" : "honey crisp", "price" : 1.99 }, 
     { "_id" : 2, "item" : "apple", "type" : "fuji", "price" : 1.99 }, 
     { "_id" : 3, "item" : "apple", "type" : "jonagold", "price" : 1.29 }, 
     { "_id" : 4, "item" : "apple", "type" : "jonathan", "price" : 1.29 }, 
     { "_id" : 5, "item" : "apple", "type" : "mcintosh", "price" : 1.29 }, 
     { "_id" : 6, "item" : "apple", "type" : "cortland", "price" : 1.29 }, 
     { "_id" : 7, "item" : "orange", "type" : "cara cara", "price" : 2.99 }, 
     { "_id" : 9, "item" : "orange", "type" : "satsuma", "price" : 1.99 }, 
     { "_id" : 8, "item" : "orange", "type" : "valencia", "price" : 0.99 }, 
     { "_id" : 10, "item" : "orange", "type" : "navel", "price" : 1.39 } 
 ]) 
 // create indexes 
 indexRes = db.products.createIndex( [ 
     { "item" : 1, "type" : 1 }, 
     { "item" : 1, "type" : -1 }, 
     { "price" : 1 } 
 ]) 
 
 writedump(indexRes) 
</cfscript>

db.collection.createIndexes

This function creates one or more indexes on a collection. For more information, see the official docs.

<cfscript> 
 db = getmongoservice("mymongodb").db("imdb"); 
 //db.products.drop() 
 db.createCollection("products") 
 // insert documents 
 db.products.insertMany([ 
     { "_id" : 1, "item" : "apple", "type" : "honey crisp", "price" : 1.99 }, 
     { "_id" : 2, "item" : "apple", "type" : "fuji", "price" : 1.99 }, 
     { "_id" : 3, "item" : "apple", "type" : "jonagold", "price" : 1.29 }, 
     { "_id" : 4, "item" : "apple", "type" : "jonathan", "price" : 1.29 }, 
     { "_id" : 5, "item" : "apple", "type" : "mcintosh", "price" : 1.29 }, 
     { "_id" : 6, "item" : "apple", "type" : "cortland", "price" : 1.29 }, 
     { "_id" : 7, "item" : "orange", "type" : "cara cara", "price" : 2.99 }, 
     { "_id" : 9, "item" : "orange", "type" : "satsuma", "price" : 1.99 }, 
     { "_id" : 8, "item" : "orange", "type" : "valencia", "price" : 0.99 }, 
     { "_id" : 10, "item" : "orange", "type" : "navel", "price" : 1.39 } 
 ]) 
 // create indexes 
 indexRes = db.products.createIndexes( [ 
     { "item" : 1, "type" : 1 }, 
     { "item" : 1, "type" : -1 }, 
     { "price" : 1 } 
 ]) 
 
 writedump(indexRes) 
</cfscript>

db.collection.dropIndex

This function removes a specified index from a collection. For more information, see the official docs.

<cfscript> 
 db = getmongoservice("mymongodb").db("imdb"); 
 //db.products.drop() 
 db.createCollection("products") 
 // insert documents 
 db.products.insertMany([ 
     { "_id" : 1, "item" : "apple", "type" : "honey crisp", "price" : 1.99 }, 
     { "_id" : 2, "item" : "apple", "type" : "fuji", "price" : 1.99 }, 
     { "_id" : 3, "item" : "apple", "type" : "jonagold", "price" : 1.29 }, 
     { "_id" : 4, "item" : "apple", "type" : "jonathan", "price" : 1.29 }, 
     { "_id" : 5, "item" : "apple", "type" : "mcintosh", "price" : 1.29 }, 
     { "_id" : 6, "item" : "apple", "type" : "cortland", "price" : 1.29 }, 
     { "_id" : 7, "item" : "orange", "type" : "cara cara", "price" : 2.99 }, 
     { "_id" : 9, "item" : "orange", "type" : "satsuma", "price" : 1.99 }, 
     { "_id" : 8, "item" : "orange", "type" : "valencia", "price" : 0.99 }, 
     { "_id" : 10, "item" : "orange", "type" : "navel", "price" : 1.39 } 
 ]) 
 // create indexes 
 createIdx=db.products.createIndex( [ 
     { "item" : 1, "type" : 1 }, 
     { "item" : 1, "type" : -1 }, 
     { "price" : 1 } 
 ]) 
 
 // drop index 
        db.products.dropIndex(createIdx) 
</cfscript>

db.collection.dropIndexes

This function removes a specified index or indexes from a collection. For more information, see the official docs.

<cfscript> 
 db = getmongoservice("mymongodb").db("imdb"); 
 //db.products.drop() 
 db.createCollection("products") 
 // insert documents 
 db.products.insertMany([ 
     { "_id" : 1, "item" : "apple", "type" : "honey crisp", "price" : 1.99 }, 
     { "_id" : 2, "item" : "apple", "type" : "fuji", "price" : 1.99 }, 
     { "_id" : 3, "item" : "apple", "type" : "jonagold", "price" : 1.29 }, 
     { "_id" : 4, "item" : "apple", "type" : "jonathan", "price" : 1.29 }, 
     { "_id" : 5, "item" : "apple", "type" : "mcintosh", "price" : 1.29 }, 
     { "_id" : 6, "item" : "apple", "type" : "cortland", "price" : 1.29 }, 
     { "_id" : 7, "item" : "orange", "type" : "cara cara", "price" : 2.99 }, 
     { "_id" : 9, "item" : "orange", "type" : "satsuma", "price" : 1.99 }, 
     { "_id" : 8, "item" : "orange", "type" : "valencia", "price" : 0.99 }, 
     { "_id" : 10, "item" : "orange", "type" : "navel", "price" : 1.39 } 
 ]) 
 // create indexes 
 createIdx=db.products.createIndex( [ 
     { "item" : 1, "type" : 1 }, 
     { "item" : 1, "type" : -1 }, 
     { "price" : 1 } 
 ]) 
 
 // drop index 
        db.products.dropIndexes(createIdx) 
</cfscript>

db.collection.getIndexes

This function decribes the existing indexes on a collection. For more information, see the official docs.

<cfscript> 
    db = getmongoservice("mymongodb").db("imdb"); 
    // db.products.drop() 
    db.createCollection("products") 
    // insert documents 
    db.products.insertMany([ 
           { "_id" : 1, "item" : "apple", "type" : "honey crisp", "price" : 1.99 }, 
           { "_id" : 2, "item" : "apple", "type" : "fuji", "price" : 1.99 }, 
           { "_id" : 3, "item" : "apple", "type" : "jonagold", "price" : 1.29 }, 
           { "_id" : 4, "item" : "apple", "type" : "jonathan", "price" : 1.29 }, 
           { "_id" : 5, "item" : "apple", "type" : "mcintosh", "price" : 1.29 }, 
           { "_id" : 6, "item" : "apple", "type" : "cortland", "price" : 1.29 }, 
           { "_id" : 7, "item" : "orange", "type" : "cara cara", "price" : 2.99 }, 
           { "_id" : 9, "item" : "orange", "type" : "satsuma", "price" : 1.99 }, 
           { "_id" : 8, "item" : "orange", "type" : "valencia", "price" : 0.99 }, 
           { "_id" : 10, "item" : "orange", "type" : "navel", "price" : 1.39 } 
    ]) 
    // create indexes 
    db.products.createIndexes( [ 
           { "item" : 1, "type" : 1 }, 
           { "item" : 1, "type" : -1 }, 
           { "price" : 1 } 
    ]) 
  
    // get index 
    getRes=db.products.getIndexes() 
    writeDump(getRes) 
</cfscript>

db.collection.reIndex

This function removes all indexes on a collection and rebuilds them.. For more information, see the official docs.

<cfscript> 
    db = getmongoservice("mymongodb").db("imdb"); 
    // db.products.drop() 
    db.createCollection("products") 
    // insert documents 
    db.products.insertMany([ 
           { "_id" : 1, "item" : "apple", "type" : "honey crisp", "price" : 1.99 }, 
           { "_id" : 2, "item" : "apple", "type" : "fuji", "price" : 1.99 }, 
           { "_id" : 3, "item" : "apple", "type" : "jonagold", "price" : 1.29 }, 
           { "_id" : 4, "item" : "apple", "type" : "jonathan", "price" : 1.29 }, 
           { "_id" : 5, "item" : "apple", "type" : "mcintosh", "price" : 1.29 }, 
           { "_id" : 6, "item" : "apple", "type" : "cortland", "price" : 1.29 }, 
           { "_id" : 7, "item" : "orange", "type" : "cara cara", "price" : 2.99 }, 
           { "_id" : 9, "item" : "orange", "type" : "satsuma", "price" : 1.99 }, 
           { "_id" : 8, "item" : "orange", "type" : "valencia", "price" : 0.99 }, 
           { "_id" : 10, "item" : "orange", "type" : "navel", "price" : 1.39 } 
    ]) 
    // create indexes 
    db.products.createIndexes( [ 
           { "item" : 1, "type" : 1 }, 
           { "item" : 1, "type" : -1 }, 
           { "price" : 1 } 
    ]) 
  
    // re index 
    try{ 
        res=db.products.reIndex() 
        writeOutput("Indexes removed and re-created successfully") 
        writeDump(res) 
    } 
    catch(any e){ 
        writeDump(e) 
    } 
</cfscript>

db.collection.totalIndexSize

This function returns the total size of all the indexes in a collection.. For more information, see the official docs.

<cfscript> 
    db = getmongoservice("mymongodb").db("imdb"); 
    // db.products.drop() 
    db.createCollection("products") 
    // insert documents 
    db.products.insertMany([ 
           { "_id" : 1, "item" : "apple", "type" : "honey crisp", "price" : 1.99 }, 
           { "_id" : 2, "item" : "apple", "type" : "fuji", "price" : 1.99 }, 
           { "_id" : 3, "item" : "apple", "type" : "jonagold", "price" : 1.29 }, 
           { "_id" : 4, "item" : "apple", "type" : "jonathan", "price" : 1.29 }, 
           { "_id" : 5, "item" : "apple", "type" : "mcintosh", "price" : 1.29 }, 
           { "_id" : 6, "item" : "apple", "type" : "cortland", "price" : 1.29 }, 
           { "_id" : 7, "item" : "orange", "type" : "cara cara", "price" : 2.99 }, 
           { "_id" : 9, "item" : "orange", "type" : "satsuma", "price" : 1.99 }, 
           { "_id" : 8, "item" : "orange", "type" : "valencia", "price" : 0.99 }, 
           { "_id" : 10, "item" : "orange", "type" : "navel", "price" : 1.39 } 
    ]) 
    // create indexes 
    db.products.createIndexes( [ 
           { "item" : 1, "type" : 1 }, 
           { "item" : 1, "type" : -1 }, 
           { "price" : 1 } 
    ]) 
  
    totSize=db.products.totalIndexSize() 
    writeDump(totSize) 
</cfscript>

Database methods

db.adminCommand

The db.adminCommand provides a helper function to run database commands. For more information, see the official docs.

The example below uses db.adminCommand() to execute the renameCollection database command to rename the collection collection1 in the db_source database to collection11.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  renameResponse=  db.adminCommand( 
  { 
     renameCollection: "db_source.collection1", 
     to: "db_source.collection11" 
  } 
) 
  writeDump(renameResponse) 
</cfscript>

db.createCollection

Creates a collection. You can also use this method to create a capped collection. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  isSuccessful=db.createCollection("log", { capped : true, size : 5242880, max : 5000 } ) 
  writeDump(isSuccessful) 
</cfscript>

db.createView

This function Creates a view as the result of the applying the specified aggregation pipeline to the source collection or view. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  // create a collection 
  db.createCollection("survey") 
  db.survey.insertMany([ 
    { _id: 1, empNumber: "abc123", feedback: { management: 3, environment: 3 }, department: "A" }, 
    { _id: 2, empNumber: "xyz987", feedback: { management: 2, environment: 3 }, department: "B" }, 
    { _id: 3, empNumber: "ijk555", feedback: { management: 3, environment: 4 }, department: "A" } 
  ]) 
  // create view 
  viewResponse=db.createView( 
   "managementFeedback", 
   "survey", 
   [ { $project: { "management": "$feedback.management", department: 1 } } ] 
  ) 
  writeDump(viewResponse) 
</cfscript>

db.currentOp

This function Returns a document that contains information on in-progress operations for the database instance. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  // The following example returns information on all active operations for 
  // database db_source that have been running longer than 3 seconds 
  currentOpResponse=db.currentOp( 
   { 
     "active" : true, 
     "secs_running" : { "$gt" : 3 }, 
     "ns" : /^db_source\./ 
   } 
) 
writeDump(currentOpResponse) 
</cfscript>

db.getCollection

This function returns a collection object for any collection in the database. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  collectionResponse=db.getCollection("survey") 
  writeDump(collectionResponse) 
</cfscript>

db.getCollectionInfos

This function returns an array of documents with collection or view information, such as name and options, for the current database. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  collInfoResponse=db.getCollectionInfos() 
  writeDump(collInfoResponse) 
</cfscript>

db.getCollectionNames

This function returns an array containing the names of all collections and views in the current database. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  collNamesResponse=db.getCollectionNames() 
  writeDump(collNamesResponse) 
</cfscript>

db.getMongo

This function returns the current database connection. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  mongoResponse=db.getMongo() 
  writeDump(mongoResponse) 
</cfscript>

db.getName

This function returns the current name of the database. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  nameResponse=db.getName() 
  writeDump(nameResponse) 
</cfscript>

db.getSiblingDB

This function returns a database object. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  siblingResponse=db.getSiblingDB("db_source") 
  writeDump(siblingResponse) 
</cfscript>

db.hostInfo

This function returns an array with system information that the mongod or mongos runs on. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  hostInfoResponse=db.hostInfo() 
  writeDump(hostInfoResponse) 
</cfscript>

db.isMaster

This function returns an array that describes the mongod session. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  isMasterResponse=db.isMaster() 
  writeDump(isMasterResponse) 
</cfscript>

db.runCommand

This function acts as a helper for the following database commands:

Command

Description

logout

Terminates the current authenticated session.

createUser

Creates a new user.

dropAllUsersFromDatabase

Deletes all users associated with a database.

dropUser

Removes a single user.

grantRolesToUser

Grants a role and its privileges to a user.

revokeRolesFromUser

Removes a role from a user.

updateUser

Updates a user’s data.

usersInfo

Returns information about the specified users.

createUser

Creates a new user.

dropAllUsersFromDatabase

Deletes all users associated with a database.

dropUser

Removes a single user.

grantRolesToUser

Grants a role and its privileges to a user.

revokeRolesFromUser

Removes a role from a user.

updateUser

Updates a user’s data.

usersInfo

Returns information about the specified users.

createRole

Creates a role and specifies its privileges.

dropRole

Deletes the user-defined role.

dropAllRolesFromDatabase

Deletes all user-defined roles from a database.

grantPrivilegesToRole

Assigns privileges to a user-defined role.

grantRolesToRole

Specifies roles from which a user-defined role inherits privileges.

invalidateUserCache

Flushes the in-memory cache of user information, including credentials and roles.

revokePrivilegesFromRole

Removes the specified privileges from a user-defined role.

revokeRolesFromRole

Removes specified inherited roles from a user-defined role.

rolesInfo

Returns information for the specified role or roles.

updateRole

Updates a user-defined role.

delete

Deletes one or more documents.

find

Selects documents in a collection or a view.

findAndModify

Returns and modifies a single document.

getLastError

Returns the success status of the last operation.

insert

Inserts one or more documents.

resetError

Resets the last error status.

update

Updates one or more documents.

This command will fail in some cases when unordered structs are sent to it. MongoDB functions accepts keys in a certain order and while sending them via ColdFusion. Ensure that these keys are ordered. Hence for all these commands, use ordered structs .

For example,

res = db.runCommand 
([ 
    "createUser" : "mongouser2", 
    "pwd" : "testpassword", 
    "customData" : {"testUser":"ok"}, 
    "roles": [["role":"readWrite","db":dbName]] 
])

db.serverBuildInfo

This function returns a document that contains an overview of parameters used to compile this mongod instance. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  buildResponse=db.serverBuildInfo() 
  writeDump(buildResponse) 
</cfscript>

db.serverStatus

This function returns a struct that provides an overview of the database process’s state. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  serverResponse=db.serverStatus() 
  writeDump(serverResponse) 
</cfscript>

db.stats

This function returns statistics for a database. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  statsResponse=db.stats(1024) // To display kilobytes rather than bytes, specify a scale value of 1024. 
  writeDump(statsResponse) 
</cfscript>

db.version

This function returns the version of the mongo instance. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  versionResponse=db.version() 
  writeDump(versionResponse) 
</cfscript>

User Management methods

db.changeUserPassword

This function updates the password of a user.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  db.changeUserPassword("username","password") 
</cfscript>
<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  db.changeUserPassword("username",passwordPrompt()) // Prompt for a new password 
</cfscript>

db.createUser

This function creates a new user for the database on which the method is run. For more information, see the official docs.

<cfscript> 
    db = getmongoservice("mymongodb").db("db_source") // create a db 
    createResponse=db.createUser( 
   { 
     user: "User1", 
     pwd: "admin123", 
     roles: [ "readWrite", "dbAdmin" ] 
   } 
   ) 
   writeDump(createResponse) 
</cfscript>

db.dropUser

This function removes a user from the current database. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  dropResponse=db.dropUser("User1") 
  writeDump(dropResponse) 
</cfscript>

db.dropAllUsers

This function drops all users in a database. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  // create three users 
  db.createUser( 
 { 
   user: "User1", 
   pwd: "admin123", 
   roles: [ "readWrite", "dbAdmin" ] 
 } 
 ) 
 db.createUser( 
{ 
  user: "User2", 
  pwd: "admin123", 
  roles: [ "readWrite", "dbAdmin" ] 
} 
) 
db.createUser( 
{ 
 user: "User3", 
 pwd: "admin123", 
 roles: [ "readWrite", "dbAdmin" ] 
} 
) 
dropAllResponse=db.dropAllUsers({w: "majority", wtimeout: 5000}) 
writeDump(dropAllResponse) 
</cfscript> 

db.getUser

This function returns information about a specified user. For more information, see the official docs.

<cfscript> 
    db = getmongoservice("mymongodb").db("db_source") // create a db 
    // create a user 
    db.createUser( 
    { 
         user: "User1", 
         pwd: "admin123", 
         roles: [ "readWrite", "dbAdmin" ] 
    } 
    ) 
    getUserResponse=db.getUser("User1") 
    writeDump(getUserResponse) 
</cfscript>

db.getUsers

This function returns information about all users in the database. For more information, see the official docs.

<cfscript> 
db = getmongoservice("mymongodb").db("db_source") // create a db 
// create three users 
db.createUser( 
{ 
 user: "User11", 
 pwd: "admin123", 
 roles: [ "readWrite", "dbAdmin" ] 
} 
) 
db.createUser( 
{ 
user: "User12", 
pwd: "admin123", 
roles: [ "readWrite", "dbAdmin" ] 
} 
) 
db.createUser( 
{ 
user: "User13", 
pwd: "admin123", 
roles: [ "readWrite", "dbAdmin" ] 
} 
) 
getUsersResponse=db.getUsers() 
writeDump(getUsersResponse) 
</cfscript>

db.grantRolesToUser

This function grants roles to a user. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  // create a user 
  db.createUser( 
  { 
   user: "User001", 
   pwd: "admin123", 
   roles: ["dbAdmin"] 
  } 
  ) 
  grantRoleResponse=db.grantRolesToUser("User001",["read","readWrite"]) 
  writeDump(grantRoleResponse) 
</cfscript>

db.revokeRolesFromUser

This function removes a one or more roles from a user on the current database. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  revokeRoleResponse=db.revokeRolesFromUser("User001",["read","readWrite"]) 
  writeDump(revokeRoleResponse) 
</cfscript>

db.updateUser

This function updates the user’s profile on the database. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  updateRole={ 
    roles:["read","readWrite"] 
  } 
  updateUserResponse=db.updateUser("User001",updateRole) 
  writeDump(updateUserResponse) 
</cfscript>

Role Management methods

db.createRole

This function creates a role in the database. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  roleDocument={ 
    "role": "newRead", 
    "privileges": [ 
    [ resource: [ db: "db_source" , collection: "" ], 
       actions: [ "find", "createCollection", "dbStats", "collStats" ] ] 
    ], 
    "roles":[] 
  } 
  createRoleResponse=db.createRole(roleDocument) 
  writeDump(createRoleResponse) 
</cfscript>

db.dropRole

This function deletes a user-defined role from the database. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source_1") // create a db 
  // create a user defined role 
  dbName="db_source_1" 
  db.createRole( 
[ 
  role: "customrole1", 
  privileges: [ 
       [ resource: [ db: dbName , collection: "" ], 
         actions: [ "find", "createCollection", "dbStats", "collStats" ] ], 
       [ resource: [ db: dbName, collection: "logs" ], 
         actions: [ "insert" ] ], 
       [ resource: [ db: dbName, collection: "data" ], 
         actions: [ "insert", "update", "remove", "compact" ] ], 
       [ resource: [ db: dbName, collection: "system.js" ], 
         actions: [ "find" ] ] 
  ], 
  roles : [["role":"userAdmin","db":dbName], 
  ["role":"readWrite","db":dbName] 
 ] 
]) 
    dropRoleResponse=db.dropRole("customrole1") 
    writeDump(dropRoleResponse) 
</cfscript> 

db.dropAllRoles

This function deletes all user-defined roles on the database.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source_1") // create a db 
  dbName="db_source_1" 
  // create three custom roles 
  db.createRole( 
[ 
  role: "customrole11", 
  privileges: [ 
       [ resource: [ db: dbName , collection: "" ], 
         actions: [ "find", "createCollection", "dbStats", "collStats" ] ], 
       [ resource: [ db: dbName, collection: "logs" ], 
         actions: [ "insert" ] ], 
       [ resource: [ db: dbName, collection: "data" ], 
         actions: [ "insert", "update", "remove", "compact" ] ], 
       [ resource: [ db: dbName, collection: "system.js" ], 
         actions: [ "find" ] ] 
  ], 
  roles : [["role":"userAdmin","db":dbName], 
  ["role":"readWrite","db":dbName] 
 ] 
]) 
 
db.createRole( 
[ 
role: "customrole12", 
privileges: [ 
     [ resource: [ db: dbName , collection: "" ], 
       actions: [ "find", "createCollection", "dbStats", "collStats" ] ], 
     [ resource: [ db: dbName, collection: "logs" ], 
       actions: [ "insert" ] ], 
     [ resource: [ db: dbName, collection: "data" ], 
       actions: [ "insert", "update", "remove", "compact" ] ], 
     [ resource: [ db: dbName, collection: "system.js" ], 
       actions: [ "find" ] ] 
], 
roles : [["role":"userAdmin","db":dbName], 
["role":"readWrite","db":dbName] 
] 
]) 
    dropAllRolesResponse=db.dropAllRoles({ w: "majority" }) 
    writeDump(dropAllRolesResponse) 
</cfscript> 

db.getRole

This function returns the roles from which this role inherits privileges. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source_1") // create a db 
  getRoleResponse=db.getRole("newRead",{ 
    "showBuiltinRoles":true, 
    "showPrivileges":true 
  }) 
  writeDump(getRoleResponse) 
</cfscript>

db.getRoles

This function retrieves information of all the roles in the database. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source_1") // create a db 
  getAllRolesResponse=db.getRoles( 
  { 
    rolesInfo: 1, 
    showPrivileges:true, 
    showBuiltinRoles: true 
  } 
  ) 
  writeDump(getAllRolesResponse) 
</cfscript>

db.grantPrivilegesToRole

This function grants additional privileges to a user-defined role. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  dbName="db_source" 
  grantResponse=db.grantPrivilegesToRole("newRead", 
  [ 
  { 
    resource: { db: dbName, collection: "" }, 
    actions: [ "insert" ] 
  }, 
  { 
    resource: { db: dbName, collection: "system.js" }, 
    actions: [ "find" ] 
  } 
] 
  ) 
  writeDump(grantResponse) 
</cfscript>

db.revokePrivilegesFromRole

This function removes specified specified privileges from the user-defined role on the database. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  dbName="db_source" 
  // create a user defined role 
  db.createrole( 
  [ 
  role: "customrole005", 
  privileges: [ 
       [ resource: [ db: dbName , collection: "" ], 
         actions: [ "find", "createCollection", "dbStats", "collStats" ] ], 
       [ resource: [ db: dbName, collection: "logs" ], 
         actions: [ "insert" ] ], 
       [ resource: [ db: dbName, collection: "data" ], 
         actions: [ "insert", "update", "remove", "compact" ] ], 
       [ resource: [ db: dbName, collection: "system.js" ], 
         actions: [ "find" ] ] 
  ], 
  roles : [["role":"userAdmin","db":dbName], 
  ["role":"readWrite","db":dbName] 
 ] 
]) 
  revokeResponse=db.revokePrivilegesFromRole("customrole002", 
  [ 
  { 
    resource: { db: dbName, collection: "" }, 
    actions: [ "find","createCollection" ] 
  }, 
  { 
    resource: { db: dbName, collection: "system.js" }, 
    actions: [ "find" ] 
  } 
] 
  ) 
  writeDump(revokeResponse) 
</cfscript>

db.grantRolesToRole

This function grants roles to a user-defined role. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  grantRoleUDR=db.grantRolesToRole("customrole005",["read"]) 
  writeDump(grantRoleUDR) 
</cfscript>

db.revokeRolesFromRole

This function removes the specified inherited roles from a role. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  revokeRoleUDR=db.revokeRolesFromRole("customrole005",["read"]) 
  writeDump(revokeRoleUDR) 
</cfscript>

db.updateRole

This function updates a user-defined role. For more information, see the official docs.

<cfscript> 
  db = getmongoservice("mymongodb").db("db_source") // create a db 
  dbName="db_source" 
  roleDocument={ 
    privileges:[ 
    [ resource: [ db: dbName , collection: "" ], 
       actions: [ "find", "createCollection", "dbStats", "collStats" ] ] 
    ], 
    roles:["read","readWrite"] 
  } 
  updateRoleResponse=db.updateRole("customrole005",roleDocument) 
  writeDump(updateRoleResponse) 
</cfscript>

Limitations

GSSAPI authentication is not supported in MongoDB.

 Adobe

Get help faster and easier

New user?

Adobe MAX 2024

Adobe MAX
The Creativity Conference

Oct 14–16 Miami Beach and online

Adobe MAX

The Creativity Conference

Oct 14–16 Miami Beach and online

Adobe MAX 2024

Adobe MAX
The Creativity Conference

Oct 14–16 Miami Beach and online

Adobe MAX

The Creativity Conference

Oct 14–16 Miami Beach and online