WD Native access to MongoDB
// Connection to the MongoDB server on the example database (creates the database if it does not exist)
gclConnection = MongoCreate(StringBuild("mongodb://%1:%2/%3",EDT_ServerAddress,EDT_Port,BASE_WINDEV_EXAMPLE))
// Retrieves objects for accessing the database
gclBase = gclConnection.Database[BASE_WINDEV_EXAMPLE]
// Finds the example collection
gclSet = gclBase.Collection[COLLECTION_WINDEV_EXAMPLE]
// If the example collection does not exist, create it
IF gclSet=Null THEN
cOption is a mongoCollectionOption
WITH cOption
// Options used to limit the collection size
// .MaxSize: If the collection reaches or exceeds this size (in bytes), the oldest elements will be deleted
// .MaxNbDocuments: If the collection reaches or exceeds this size (in number of documents), the oldest elements will be deleted
// Validate the added documents
// .Validator: JSON document describing the format of added documents
// This validator example checks whether the document contains at least the Phone item or the Email item
.Validateur = "{ ""$or"": [ { ""Phone"": { ""$type"": ""string"" } }, { ""Email"": { ""$type"": ""string"" } } ] }"
// .ValidationLEvel: Defines how the validator is used. The possible values are:
// "off": the validator is not used
// "strict": the validator is used for the additions and the modifications
// "moderate": the validator is used for the additions, the validator is used in modification only if the modified document is valid
.NiveauValidation = "strict"
END
MongoCreateCollection(gclBase,COLLECTION_WINDEV_EXAMPLE,cOption)
gclSet = gclBase.Collection[COLLECTION_WINDEV_EXAMPLE]
END
gclGridFS..Database = gclBase
gclGridFS..Prefix = GRIDFS_WINDEV_EXAMPLE
GR_AVAIL_COLLECTION..State = Active
RefreshDocumentTable()
Toast("Connection to MongoDB database and collection opening successful.")
//--------------------------------------------------------------------------------------------------------------------------------------
// Conexão com o servidor MongoDB no banco de dados de exemplo (cria o banco de dados se ele não existir)
gclConnection = MongoCreate(StringBuild("mongodb://%1:%2/%3",EDT_ServerAddress,EDT_Port,BASE_WINDEV_EXAMPLE))
// Recupera objetos para acessar o banco de dados
gclBase = gclConnection.Database[BASE_WINDEV_EXAMPLE]
// Encontra a coleção de exemplo
gclSet = gclBase.Collection[COLLECTION_WINDEV_EXAMPLE]
// Se a coleção de exemplo não existir, crie-a
IF gclSet=Nulo ENTÃO
cOption é uma mongoCollectionOption
COM cOpção
// Opções usadas para limitar o tamanho da coleção
// .MaxSize: Se a coleção atingir ou ultrapassar este tamanho (em bytes), os elementos mais antigos serão excluídos
// .MaxNbDocuments: Se a coleção atingir ou ultrapassar esse tamanho (em número de documentos), os elementos mais antigos serão excluídos
// Valida os documentos adicionados
// .Validator: documento JSON que descreve o formato dos documentos adicionados
// Este exemplo de validador verifica se o documento contém pelo menos o item Telefone ou o item Email
.Validador = "{ ""$ou"": [ { ""Telefone"": { ""$tipo"": ""string"" } }, { ""E-mail"": { ""$tipo"" : ""corda"" } } ] }"
// .ValidationLEvel: Define como o validador é usado. Os valores possíveis são:
// "off": o validador não é usado
// "strict": o validador é usado para as adições e modificações
// "moderado": o validador é usado para as adições, o validador é usado na modificação somente se o documento modificado for válido
.NiveauValidation = "estrito"
FIM
MongoCreateCollection(gclBase,COLLECTION_WINDEV_EXAMPLE,cOption)
gclSet = gclBase.Collection[COLLECTION_WINDEV_EXAMPLE]
FIM
gclGridFS..Database = gclBase
gclGridFS..Prefix = GRIDFS_WINDEV_EXAMPLE
GR_AVAIL_COLLECTION..State = Ativo
RefreshDocumentTable()
Toast("Conexão ao banco de dados MongoDB e abertura de coleção bem-sucedida.");
//--------------------------------------------------------------------------------------------------------------------------------------
// Read information about the current database
clInfo is a mongoDatabaseInfo = MongoInfo(gclBase)
WITH clInfo
sInfo is string = StringBuild([
Information about MongoDB database
--------------------------------
Database name: %1
Number of collections: %2
Number of documents: %3
Average size of documents: %4
Total database size: %5
Total storage size: %6
],
.Nom,
.NbCollections,
.NbDocuments,
LengthToString(.TailleMoyenneDocument),
LengthToString(.TailleDonnées),
LengthToString(.TailleStockage))
END
Info(sInfo)
//--------------------------------------------------------------------------------
// Variable containing the document that will be added into the database
stContact_table is STContactInfo
WITH stContact_table
.Name = "DURAND"
.FirstName = "John"
.Phone = "+33467032032"
.Email = "j.doe@WINDEV.com"
END
// To add a document into a MongoDB database, it must be serialized in JSON beforehand
sBufferJSON is string
Serialize(stContact_table,sBufferJSON,psdJSON)
MongoAdd(gclSet,sBufferJSON)
RefreshDocumentTable()
Toast("Addition successful")
//---------------------------------------------------------------------
// Variable containing the documents that will be added into the database
arrDocument is array of strings
// Temporary variables
stContact_table is STContactInfo
sBufferJSON is string
// Build the array of documents
stContact_table = [ "MOORE", "Elodie", "+33.467032032", "e.moore@WINDEV.com" ]
Serialize(stContact_table,sBufferJSON,psdJSON)
Add(arrDocument, sBufferJSON)
stContact_table = [ "SMITH", "Tommy", "+33.467032032", "r.smith@WINDEV.com" ]
Serialize(stContact_table,sBufferJSON,psdJSON)
Add(arrDocument, sBufferJSON)
stContact_table = [ "HUDSON", "Jade", "+33.467032032", "j.hudson@WINDEV.com" ]
Serialize(stContact_table,sBufferJSON,psdJSON)
Add(arrDocument, sBufferJSON)
// Add the three contacts in a single call
MongoAdd(gclSet,arrDocument)
RefreshDocumentTable()
Toast("Addition successful")
//---------------------------------------------------------------------
// Define the search filter
// We want the contacts whose email address ends by "WINDEV.com"
// To do so, filter with a regular expression: @WINDEV\.com$
// The option 'i' is used to specify that the search will not be case sensitive
sFilter is string = [
{
"Email": {
"$regex": "@WINDEV.com$",
"$options": "i"
}
}
]
// Define the search options
clOption is a mongoFindOption
WITH clOption
// .Projection: Criteria for presenting documents (the controls that will be retrieved for example)
// We want to retrieve the LastName and FirstName items therefore an inclusion projection is performed (specify the items to retrieve)
.Projection = "{ ""LastName"": 1, ""FirstName"": 1 }"
// If we wanted to retrieve all the items EXCEPT for the phone, an exclusion projection could be performed:
// .Projection = "{ Phone: 0 }"
// .Limite: Maximum number of documents to return
// Retrieve up to 10 documents
.Limite = 10
// .Sort: Sort criterion of returned documents
.Sort = ""
// .Ignore: Exclusion criterion, the documents that correspond to this criterion are ignored
.Ignore = ""
END
// Starts the search and displays all the documents found in the trace
r is a mongoResult dynamic = MongoFind(gclSet, sFilter, clOption)
TableDeleteAll(TABLE_Contacts)
// To read all the documents, don't specify any search filter
FOR EACH v OF r
v2 is Variant = v
TableAddLine(TABLE_Contacts,v2.Name,v2.FirstName,v2.Phone,v2.Email)
END
//----------------------------------------------------------------------
// Find the first contact whose "FirstName" member is set to "Jack" and modifies it to "Joey"
// Search filter
sFilter is string = "{ ""FirstName"": ""Jack"" }"
// Modification criterion
sModification is string = "{ ""$set"": { ""FirstName"": ""Joey"" } }"
MongoModifyOne(gclSet,sFilter,sModification)
RefreshDocumentTable()
//-------------------------------------------------------------------------
// Find all the contacts whose "LastName" member is set to "SMITH" and modifies them to "PAULSON"
// Search filter
sFilter is string = "{ ""LastName"": ""SMITH"" }"
// Modification criterion
sModification is string = "{ ""$set"": { ""LastName"": ""PAULSON"" } }"
MongoModifyAll(gclSet,sFilter,sModification)
RefreshDocumentTable()
//----------------------------------------------------------------------------
// Deletes the first contact whose "FirstName" member is set to "Joey"
// Search filter
sFilter is string = "{ ""FirstName"": ""Joey"" }"
MongoDeleteOne(gclSet,sFilter)
RefreshDocumentTable()
//---------------------------------------------------------------------
// Deletes all the contacts whose "FirstName" member is "Robert"
// Search filter
sFilter is string = "{ ""FirstName"": ""Robert"" } "
MongoDeleteAll(gclSet,sFilter)
RefreshDocumentTable()
//-----------------------------------------------------------------------------
MongoDeleteCollection(gclSet)
TableDeleteAll(TABLE_Contacts)
GR_AVAIL_COLLECTION..State = Grayed
//-------------------------------------------------------------------------------
RefreshDocumentTable()
// Summary: Refreshes the table control that displays the list of documents found in the MongoDB collection
// Syntax:
// RefreshDocumentTable ()
//
// Parameters:
// None
// Return value:
// None
//
PROCEDURE RefreshDocumentTable()
TableDeleteAll(TABLE_Contacts)
// To read all the documents, specify an empty search filter
r is a mongoResult dynamic = MongoFind(gclSet, "{ }" )
FOR EACH v OF r
v2 is Variant = v
TableAddLine(TABLE_Contacts,v2.Name,v2.FirstName,v2.Phone,v2.Email)
END
//------------------------------------------------------------------------------------------------------------------------
// Summary: <specify the action of the procedure>
// Syntax:
// RefreshBrowsingTableGridFS ()
//
// Parameters:
// None
// Return value:
// None
//
PROCEDURE RefreshBrowsingTableGridFS()
TableDeleteAll(TABLE_GridFS)
//trace(MongoGridFSFileList(fsVV))
arrFile is array of mongoGridFSFileInfo = MongoGridFSListFile(gclGridFS)
fic is a mongoGridFSFileInfo
FOR EACH fic OF arrFile
TableAddLine(TABLE_GridFS,VariantToJSON(fic..Id),fic..Filename,fic..Date,fic..Md5,fic..Size,fic..ChunkSize,fic..ContentType)
END
TableSelectMinus(TABLE_GridFS)
GR_SELECTED_FILE..State = Grayed
//--------------------------------------------------------------------------------------------
InfoBuild([
Information about the selected file:
Identifier: %1
Name: %2
Size: %3
Size of file chuncks: %4
Creation date: %5
MD5 hash: %6
MIME type: %7
],COL_ID,TABLE_GridFS.SET_NAME,LengthToString(COL_Size),LengthToString(SET_Chunck),DateToString(COL_CreationDate),COL_MD5,COL_MIME)
//------------------------------------------------------------------------
sFile is string = fSelect("","","Select the file to send into GridFS","All the files (*.*)"+TAB+"*.*","",fselOpen)
IF sFile<>"" THEN
MongoGridFSSendFile(gclGridFS,sFile,fExtractPath(sFile,fFileName+fExtension))
Toast("Sending successfully completed.")
RefreshBrowsingTableGridFS()
END
//-----------------------------------------------------------------------------------------------------
// Summary: <specify the action of the procedure>
// Syntax:
// RefreshBrowsingTableGridFS ()
//
// Parameters:
// None
// Return value:
// None
//
PROCEDURE RefreshBrowsingTableGridFS()
TableDeleteAll(TABLE_GridFS)
//trace(MongoGridFSFileList(fsVV))
arrFile is array of mongoGridFSFileInfo = MongoGridFSListFile(gclGridFS)
fic is a mongoGridFSFileInfo
FOR EACH fic OF arrFile
TableAddLine(TABLE_GridFS,VariantToJSON(fic..Id),fic..Filename,fic..Date,fic..Md5,fic..Size,fic..ChunkSize,fic..ContentType)
END
TableSelectMinus(TABLE_GridFS)
GR_SELECTED_FILE..State = Grayed
//-------------------------------------------------------------------------------------------------
sDir is string = fSelectDir(SysDir(srDownloads),"Select the download directory")
IF sDir<>"" THEN
MongoGridFSGetFile(gclGridFS,TABLE_GridFS.SET_NAME,CompleteDir(sDir)+TABLE_GridFS.SET_NAME)
Toast("Retrieval successfully ended.")
END
//----------------------------------------------------------------------------
MongoGridFSDeleteFile(gclGridFS,TABLE_GridFS.SET_NAME)
Toast("Deletion successfully ended.")
RefreshBrowsingTableGridFS()