RDBMS
MongoDB is a cross-platform document-based NoSQL database. It uses JSON/BSON like documents with schema.
The following are some of the features of MongoDB.
For more information on the features of MongoDB, see the MongoDB official website.
To install MongoDB for your OS, see the MongoDB download center.
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:
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:
Wait for the MongoDB package to get installed.
Install from ColdFusion Administrator
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 } } }
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.
CFC: CFIDE.adminapi.nosql_datasource
Creates or modifies a MongoDb datasource.
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
<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>
Returns a structure containing all data sources or a specified data source.
public any getDatasources (dsnName)
<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>
Deletes the specified data source.
public void deleteMongoDatasource ( required dsnName )
<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>
Verifies a given data source name.
public Any verifyMongoDatasource ( required dsnName )
<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 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>
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.
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>
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>
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>
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>
You can update a collection using these methods:
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>
Employee.cfc
component accessors="true" { property string empName; property numeric age; property string dept; }
<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>
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>
<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>
<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>
<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" />
<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>
<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>
<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>
<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>
<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>
<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>
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>
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>
<cfscript> db = getmongoservice("mymongodb").db("mynewdb") // create a db db.dropDatabase() // Removes the database </cfscript>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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.
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>
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.
<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>
<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 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.
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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]] ])
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
This function grants roles to a user-defined role.
<cfscript> db = getmongoservice("mymongodb").db("db_source") // create a db grantRoleUDR=db.grantRolesToRole("customrole005",["read"]) writeDump(grantRoleUDR) </cfscript>
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>
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>
GSSAPI authentication is not supported in MongoDB.
Zaloguj się na swoje konto