Tutorial to Predict Gold Prices using Mindsdb and MongoDB
Tags: beginners, mindsdb, ai, mongodb
Published: 2023-02-24 10:33:43

## What is MindsDB?
Data that lives in your database is a valuable asset. MindsDB enables you to use your data and make forecasts. It speeds up the ML development process by bringing machine learning into the database.

With MindsDB, you can build, train, optimize, and deploy your ML models without the need for other platforms. And to get the forecasts, simply query your data and ML models. Read along to see some examples.

## What are AI Tables?
MindsDB brings machine learning into databases by employing the concept of AI Tables.

AI Tables are machine learning models stored as virtual tables inside a database. They facilitate making predictions based on your data. You can perform time series, regression, and classification predictions within your database and get the output almost instantly by querying an AI Table with simple SQL statements.

## What will we be learning in this tutorial?
**Part 1 : Setting up the requirements**

First and foremost, we will prepare our setup that is essential to start forecasting with MindsDB and MongoAPI.

1. Download MongoDB and MongoDB Compass
2. Getting started with MindsDB
3. Integrating MindsDB with MongoDB

**Part 2 : Generating ML Models**

We will see how to create and train ML models in our database. In this tutorial, we will be predicting the gold price using [this dataset](https://www.kaggle.com/datasets/arashnic/learn-time-series-forecasting-from-gold-price).

1. Preparing the database
2. Understanding our Problem Statement
3. Creating the Predictor Model
4. Querying the Predictor Model

## Part 1 : Setting up the requirements
We will be explaining this section briefly, so that we can move on to our predictions.

**Download MongoDB and MongoDB Compass**

To get started we must have both [MongoDB Community Edition](https://www.mongodb.com/try/download/community) and [MongoDB Compass](https://www.mongodb.com/try/download/compass) installed and working in our systems.

Once you are done with the installation of both MongoDB and MongoDB Compass we can get going with our tutorial.

**Getting started with MindsDB**

MindsDB provides all users with a free MindsDB Cloud version that they can access to generate predictions on their database. You can sign up for the free [MindsDB Cloud Version](https://cloud.mindsdb.com/) by following the [setup guide](https://docs.mindsdb.com/setup/cloud/). Verify your email and log into your account and you are ready to go. Once done, you should be seeing a page like this :

![MindsDB Cloud dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yoq08e49oj0a1vzaiwzg.png)

If you wish, you can choose to install MindsDB on your local system using docker image or by using [PyPI](https://pypi.org/project/MindsDB/). However, we will be working with Minds DB Cloud in this tutorial.

**Integrating MindsDB with MongoDB**

MindsDB provides us the ability to integrate with MongoDB using the MongoAPI. We can do so by following the given steps.

Open your MongoDB Compass. On the left navigation panel, You will have an option for a New Connection. Click on that Option and you will be provided with the details of your connection.

In the URI Section enter the following :

```
mongodb://cloud.mindsdb.com/
```

Click on the Advanced Connection Options dropdown. Here your host will be detected as MindsDB Cloud.

In the Authentication option enter your MindsDB Username and Password. Then click on Save and Connect, give your connection a name and select and color.

![MongoDB Compass](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yj9ek5pzofn0lxajpawt.png)

If you successfully create a connection you will be displayed a page similar to this :

![MongoDB Compass  Connection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tk4gdzwj5816fcxl189g.png)

In the bottom panel of this page, you will see the the Mongo Shell bar, enlarge it and type the following queries and click Enter.

```
> use mindsdb
> show collections
```

![Mongo Shell Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z5e1kv1qa81mn30fi04f.png)

If you get a result like this, it means that we have succeeded in integrating MindsDB with MongoDB. Now let us move to the second part of our tutorial where we will be generating an ML model.

## Part 2 : Generating ML Models
**Preparing the database**

We will be preparing our database on which we can run our queries and perform our forecasts. On the MindsDB Cloud console, click on the last icon in the left navigation bar. You will see a 'Select Your Data Sources' page. We can add a variety of data sources, however, for this tutorial we will be working with .csv files.

Go to the files section and click on Import File. Import your csv file and provide a name for your database table in which the contents of the .csv file will be stored. Click on Save and Continue.

![Database Upload](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8l34iqk0kvajz7qcem70.png)

We need to import the data to our MongoDB database. We can use the databases.insertOne() command for this purpose.

To do so, go to the Mongo Shell and type the following command :

```
db.databases.insertOne({
    name: "gold_price", // database name
    engine: "mongodb", // database engine 
    connection_args: {
        "port": 27017, // default connection port
        "host": "mongodb+srv://readonly:6CKCDJFzLIxOtKhu@cluster0.uhsuhui.mongodb.net/test", // connection host
        "database": "gold_price" // database connection          
    }
});
```

On clicking Enter, you must receive the following response :

```
{
  acknowledged: true,
  insertedId: ObjectId("63f87788011bd9118e88fa8e")
}
```

If you get such a response, that means your database is successfully created!

**Understanding our Problem Statement**

We saw earlier that we will be predicting the gold price using this [Kaggle dataset](https://www.kaggle.com/datasets/arashnic/learn-time-series-forecasting-from-gold-price). Let us take a closer look into our database that we have set up. Our database consists of the following fields :

- DATE : Date. There is no timestamp in this field.
- VALUE : The price of gold at that date.

We can run the following query in our MindsDB Console to see our database where we can see all our fields :

```
SELECT * FROM files.gold_price LIMIT 10;
```

This is what will be displayed :

![Database fields](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jhr8y4u3lp93sprl4pb1.png)

Now let us understand what we are trying to predict. We have been given a database consisting of various fields and we want to predict the gold price according to its features. We are going to train an ML model that learns how the gold price varies according to the features. And once we have trained our model, we can input the details of a house and our ML Model will predict what its gold price will be.

Sounds like a difficult task? Let us see how MindsDB can do that for us in a simple query!

**Creating the Predictor Model**

Now that our database is ready, we can go ahead and create our ML Model. As we have seen, The Predictor Model is basically a trained Machine Learning Model that can be used to predict or forecast a particular value known as the target variable or target value.

go to the Mongo Shell and type the following command :

```
db.predictors.insert({ name: "gold_price_predictor", predict: "Value", connection: "gold_price", "select_data_query": "db.gold_price.find()" });
```

What do those parameters mean?

- name: name by which mindsdb identifies the predictor
- predict: name of the column in the database which values we want to predict
- connection: name we created previously by which Mindsdb identifies the connection
- select_data_query: this allows to specify specific rows in the database by using standard MongoDB queries. For this example, we will use all rows.

If there are no hiccups, we will get a Query Successfully Completed message.

```
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("63f89055011bd9118e88fa8f")
  }
}
```

And that’s it! We have created and trained a Machine Learning model by a single query! That is the magic of MindsDB!

**Querying the Predictor Model**

We can see our machine learning model specifications by typing the following command in our Mongo Shell :
 
```
db.predictors.find({name:"gold_price_predictor"})
```

When we press Enter we get all the details of our Predictor Model like its status, accuracy, target value and errors.

```
{
  NAME: 'gold_price_predictor',
  ENGINE: 'lightwood',
  PROJECT: 'mindsdb',
  VERSION: 1,
  STATUS: 'complete',
  ACCURACY: 0.999,
  PREDICT: 'Value',
  UPDATE_STATUS: 'up_to_date',
  MINDSDB_VERSION: '23.2.4.0',
  ERROR: null,
  SELECT_DATA_QUERY: 'db.gold_price.find()',
  TRAINING_OPTIONS: "{'target': 'Value', 'using': {}}",
  TAG: null,
  CREATED_AT: 2023-02-24T10:24:21.748Z
}
```


Now finally we can query our ML model to predict the target value of a particular entry.

The query for that is :


```
db.gold_price_predictor.find({
Date: "2020-03-14"})
```


And lo and behold! Our model predicts the gold price according to its attributes entered by us :

```
{
  Date: '2020-03-14',
  Value: 1626.129947757658,
  select_data_query: null,
  when_data: null,
  Value_original: null,
  Value_confidence: 0.99,
  Value_explain: '{"predicted_value": 1626.129947757658, "confidence": 0.99, "anomaly": null, "truth": null, "confidence_lower_bound": 1460.0741799353673, "confidence_upper_bound": 1792.185715579949}',
  Value_anomaly: null,
  Value_min: 1460.0741799353673,
  Value_max: 1792.185715579949
}
```

## Conclusion :
Using MindsDB we have successfully created and trained a Machine Learning model in our database and unlocked the ability to generate in-database forecasts. You can visit the [MindsDB Documentation](https://docs.mindsdb.com/) to know the various features of MindsDB.

## What’s Next?
If you enjoyed following along to this tutorial, make sure to Sign Up for a free [MindsDB Cloud account](https://cloud.mindsdb.com/) and continue exploring! [Kaggle](https://www.kaggle.com/) is a great resource to find similar datasets and you can create and train an ML model of your own with the help of MindsDB. You can also check them out on [GitHub](https://github.com/mindsdb/mindsdb).