« MBS @ FMTraining.TV | Home | MBS FileMaker Plugin,… »

Insert record to MongoDB in Xojo

Some of your clients may have MongoDB databases and your application may need to connect and insert a record. Here is a bit of sample code on how to this:

Sub Action() // prepare URI to servers Dim URI As New MongoURIMBS("mongodb://localhost/") // optionally with authentication 'URI.UserName = "test" 'URI.Password = "secret" // connect Dim client As New MongoClientMBS(URI) // pick database Dim database As MongoDatabaseMBS = client.Database("test") // pick collection Dim collection As MongoCollectionMBS = database.Collection("clients") // now build a record as JSON Dim NewRecord As New JSONItem NewRecord.Value("firstName") = "Bob" NewRecord.Value("lastName") = "Jones" NewRecord.Value("city") = "Los Angeles" NewRecord.Value("phone") = "555-1234-567" // and insert Dim Result As String = Collection.InsertOne(NewRecord.toString) Dim j As New JSONItem(Result) Dim n As Integer = j.Lookup("insertedCount",0) If n = 1 then MessageBox "Record saved" Else MessageBox "Failed to insert: " End If Exception m As MongoExceptionMBS MessageBox m.message End Sub

As you see we use our MongoURIMBS class to prepare the connection data like the server URL, port, user name and password. Then we use MongoClientMBS class to establish a connection. We select which database and collection (table) to use and finally insert our record as JSON to it.

Optionally the new InsertMany function in the upcoming 22.4 plugin can be used to insert multiple documents at once. You would pass either a JSON Array with the records or a Xojo array with the JSON objects.

Please try and let us know if it works or whether you have questions.

01 08 22 - 09:28