Whatever message this page gives is out now! Go check it out!
| 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) |
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
}
}
}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>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>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>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><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><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><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><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><cfscript>
db = getmongoservice("mymongodb").db("newdb") // create a db
ifCapped=db.cappedLogCollection.isCapped()
writeOutput("Is collection capped: "& ifCapped)
</cfscript><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><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><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><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><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><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><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>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>{
name="John",
age="26"
}<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><cfscript>
db = getmongoservice("mymongodb").db("mynewdb") // create a db
writeDump(db)
</cfscript><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><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><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><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><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><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><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><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><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><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><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><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><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><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><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><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><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><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><cfscript>
db = getmongoservice("mymongodb").db("newdb") // create a db
ifCapped=db.cappedLogCollection.isCapped()
writeOutput("Is collection capped: "& ifCapped)
</cfscript><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
// Members collection
latencyStatsResponse=db.members.latencyStats( { histograms: true } )
writedump(latencyStatsResponse)
</cfscript><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><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><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><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
statsResponse=db.articles.stats()
writeDump(statsResponse)
</cfscript><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><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><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><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><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><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><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><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><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><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><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><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><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><cfscript>
db = mongoservice("mymongodb").db("db_source") // create a db
// Members collection
distinctResponse=db.members.distinct("instrument")
writeDump(distinctResponse)
</cfscript><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><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><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><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><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><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><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><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><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><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><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><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><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><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><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><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><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><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><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
renameResponse= db.adminCommand(
{
renameCollection: "db_source.collection1",
to: "db_source.collection11"
}
)
writeDump(renameResponse)
</cfscript><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
isSuccessful=db.createCollection("log", { capped : true, size : 5242880, max : 5000 } )
writeDump(isSuccessful)
</cfscript><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><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><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
collectionResponse=db.getCollection("survey")
writeDump(collectionResponse)
</cfscript><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
collInfoResponse=db.getCollectionInfos()
writeDump(collInfoResponse)
</cfscript><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
collNamesResponse=db.getCollectionNames()
writeDump(collNamesResponse)
</cfscript><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
mongoResponse=db.getMongo()
writeDump(mongoResponse)
</cfscript><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
nameResponse=db.getName()
writeDump(nameResponse)
</cfscript><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
siblingResponse=db.getSiblingDB("db_source")
writeDump(siblingResponse)
</cfscript><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
hostInfoResponse=db.hostInfo()
writeDump(hostInfoResponse)
</cfscript><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
isMasterResponse=db.isMaster()
writeDump(isMasterResponse)
</cfscript>| 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. |
res = db.runCommand
([
"createUser" : "mongouser2",
"pwd" : "testpassword",
"customData" : {"testUser":"ok"},
"roles": [["role":"readWrite","db":dbName]]
])<cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
buildResponse=db.serverBuildInfo()
writeDump(buildResponse)
</cfscript><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
serverResponse=db.serverStatus()
writeDump(serverResponse)
</cfscript><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><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
versionResponse=db.version()
writeDump(versionResponse)
</cfscript><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><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
createResponse=db.createUser(
{
user: "User1",
pwd: "admin123",
roles: [ "readWrite", "dbAdmin" ]
}
)
writeDump(createResponse)
</cfscript><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
dropResponse=db.dropUser("User1")
writeDump(dropResponse)
</cfscript><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><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><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><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><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
revokeRoleResponse=db.revokeRolesFromUser("User001",["read","readWrite"])
writeDump(revokeRoleResponse)
</cfscript><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
updateRole={
roles:["read","readWrite"]
}
updateUserResponse=db.updateUser("User001",updateRole)
writeDump(updateUserResponse)
</cfscript><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><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><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><cfscript>
db = getmongoservice("mymongodb").db("db_source_1") // create a db
getRoleResponse=db.getRole("newRead",{
"showBuiltinRoles":true,
"showPrivileges":true
})
writeDump(getRoleResponse)
</cfscript><cfscript>
db = getmongoservice("mymongodb").db("db_source_1") // create a db
getAllRolesResponse=db.getRoles(
{
rolesInfo: 1,
showPrivileges:true,
showBuiltinRoles: true
}
)
writeDump(getAllRolesResponse)
</cfscript><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><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><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
grantRoleUDR=db.grantRolesToRole("customrole005",["read"])
writeDump(grantRoleUDR)
</cfscript><cfscript>
db = getmongoservice("mymongodb").db("db_source") // create a db
revokeRoleUDR=db.revokeRolesFromRole("customrole005",["read"])
writeDump(revokeRoleUDR)
</cfscript><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>