Effortless Data Storage: MongoDB Database and Raspberry Pi Pico W Walkthrough - Part 1

Storing data into the MongoDB Database is very easy with the Raspberry Pi Pico W. The only thing we need is an active internet connection and we can insert data through their Data API in a few steps. Also, it is all free to get started and this can provide powerful use cases to an IoT application. It can be particularly useful when working with slow-moving data.

Also, MongoDB is a NoSQL database which means it uses a BSON format to insert more complex data structures than traditional databases, which also has its Pros. It has its cons as well, one of them being that it can be slower to query data due to the nature of NoSQL; I will discuss the Pros and Cons in more detail in Part 2.

Before reading the remainder, be sure to subscribe and support the channel if you have not!

Subscribe:

Youtube

Support:

https://www.buymeacoffee.com/mmshilleh

 

Step 1-) MongoDB Account Setup

  • Go to mongodb.com and create a free account
  • Enable Data API in your account
  • Step through and generate an API Key, you will need to save the API key along with the URL they give you so you can access the cluster through an API call with the Raspberry Pi Pico W.
  • Create a database and collection in the UI, this is where we will store our example document.

Step 2-) Code

The code on the Pico W is as follows

import machine
import urequests as requests
import network
import time

import constants


def connect_to_wifi(ssid, psk):
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(ssid, psk)

    while not wlan.isconnected() and wlan.status() >= 0:
        print("Waiting to Connect")
        time.sleep(10)
    if not wlan.isconnected():
        raise Exception("Wifi not available")
    print("Connected to WiFi")


try:
    connect_to_wifi(constants.INTERNET_NAME, constants.INTERNET_PASSWORD)
    # Need to substitute from DATA API
    url = "<url>/action/insertOne"
    headers = { "api-key": "<api key>" }

    documentToAdd = {"device": "MyPico", "readings": [77, 80, 40, 60, 70, 80, 10]}

    insertPayload = {
        "dataSource": "Cluster0",
        "database": "WeatherData2",
        "collection": "BME2802",
        "document": documentToAdd,
    }

    print("sending...")

    response = requests.post(url, headers=headers, json=insertPayload)

    print("Response: (" + str(response.status_code) + "), msg = " + str(response.text))

    if response.status_code == 201:
        print("Added Successfully")
    else:
        print("Error")

    # Always close response objects so we don't leak memory
    response.close()

except Exception as e:
    print(e)
  • Insert your internet name, internet password, MongoDB Data API URL, and API Key accordingly in the code.
  • In the payload you need to add your cluster, database, and collection names.
  • We are simply connecting to WiFi and sending a payload to their API with extension /action/insertOne, which will allow us to insert one document. We are using some dummy data for this example!

If you set everything up correctly you should be able to see a document in your collection, congrats. If you had issues please watch on Youtube above for more details. In the next tutorial, we will be working with actual sensor data in a time series and doing other more complex data queries with their API, so stay tuned to the channel by subscribing!

Conclusion

Databases are essential in a majority of applications we use. Thankfully MongoDB with their Data API makes it incredibly easy to get started just with the use of WiFi. Hope you enjoyed this video and content. Let me know if you have any questions.

Create a free account to access full content.

All access to code and resources on ShillehTek.

Signup Now

Already a member? Sign In

Explore More on Our Blog

Create Tabular Product Descriptions on Your Shopify Store

Create Tabular Product Descriptions on Your Shopify Store

Enhance your Shopify store's product pages with our comprehensive guide on implementing tabular descriptions. Learn how to add a...

SSH Into Raspberry Pi with Tailscale VPN

SSH Into Raspberry Pi with Tailscale VPN

Effortlessly access and manage your Raspberry Pi from anywhere using Tailscale's secure mesh VPN.

Send Email with Lua and the ESP32

Send Email with Lua and the ESP32

In this tutorial, we delve into sending emails with the ESP32-S3 using Lua, focusing on the Xedge IDE's built-in SMTP...

How to Code with Lua on ESP32 with XEdge32

How to Code with Lua on ESP32 with XEdge32

Learn how to set up Xedge32 and start coding on the ESP32-S3 with Lua programming!

Stream Audio From Raspberry Pi to Local Computer

Stream Audio From Raspberry Pi to Local Computer

Discover the simplicity of streaming live audio directly from a USB microphone connected to your Raspberry Pi to...

SSH Raspberry Pi via Cell Phone

SSH Raspberry Pi via Cell Phone

This beginner-friendly guide will walk you through remotely controlling your Raspberry Pi using SSH through your cell phone.

Remotely Control Raspberry Pi via SSH from External Network

Remotely Control Raspberry Pi via SSH from External Network

Learn how to SSH into your Raspberry Pi from any network. This is critical in IoT since you can control...

Stream Video from Raspberry Pi Camera to YouTube Live

Stream Video from Raspberry Pi Camera to YouTube Live

Learn how to stream to YouTube from a Raspberry Pi Camera.

How to Connect BH1750 with Arduino: Measure Ambient Light

How to Connect BH1750 with Arduino: Measure Ambient Light

Learn how to measure ambient light for smart lighting control using Arduino and the BH1750 Light Intensity Module.

How to Connect MPU9250 and Raspberry Pi (Part 2 - Calibration)

How to Connect MPU9250 and Raspberry Pi (Part 2 - Calibration)

Learn how to calibrate the MPU9250 in Python with the Raspberry Pi to get more accurate acceleration and gyroscopic...

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.