Skip to content

Raspberry Pi Pico W MongoDB: Insert Data via API | ShillehTek

October 23, 2023

Video Tutorial (Optional)

Watch first if you want to follow along with the full walkthrough in real time.

Project Overview

In this project, you use a Raspberry Pi Pico W with the MongoDB Data API to insert a document into a MongoDB database over WiFi. This is a simple way to store IoT data in the cloud using an API call and a free MongoDB account to get started.

MongoDB is a NoSQL database that stores data in BSON format, which supports more complex data structures than traditional relational databases.

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

Subscribe: Youtube

Support: https://www.buymeacoffee.com/mmshilleh

  • Time: 20 to 40 minutes
  • Skill level: Beginner
  • What you will build: A Pico W script that connects to WiFi and inserts one document into MongoDB using the Data API

Parts List

From ShillehTek

  • None linked in the original article

External

  • Raspberry Pi Pico W
  • WiFi network credentials (SSID and password)
  • MongoDB account (free tier) with Data API enabled
  • MongoDB Data API key and endpoint URL

Note: You must have an active internet connection for the Pico W, and you must enable the MongoDB Data API and generate an API key to authenticate requests.

Step-by-Step Guide

Step 1 - Set up MongoDB and enable the Data API

Goal: Create a MongoDB setup that can accept insert requests from your Raspberry Pi Pico W.

What to do: In your MongoDB account:

  • Go to mongodb.com and create a free account.
  • Enable the Data API in your account.
  • Step through and generate an API Key. Save both the API key and the URL MongoDB provides so your Pico W can access the cluster through an API call.
  • Create a database and a collection in the UI. This is where you will store the example document.
MongoDB account setup screen showing Data API enablement options for use with a Raspberry Pi Pico W
MongoDB setup: enable the Data API and follow the prompts.
MongoDB Data API configuration screen showing API endpoint information needed by a Raspberry Pi Pico W
Save the Data API URL shown in your MongoDB project.
MongoDB UI showing database and collection creation for storing Pico W documents via the Data API
Create a database and collection where the Pico W will insert documents.

Expected result: You have a MongoDB cluster with the Data API enabled, an API key and URL saved, and a database and collection created.

Step 2 - Add the Pico W code and insert one document

Goal: Connect the Raspberry Pi Pico W to WiFi and send an /action/insertOne request to MongoDB Data API.

What to do: Update the code with your internet name, internet password, MongoDB Data API URL, and API key.

  • Insert your internet name and internet password in your constants file.
  • Set the MongoDB Data API URL and API key in the script.
  • In the payload, set your cluster (dataSource), database, and collection names.
  • The request uses the Data API endpoint extension /action/insertOne to insert one document (dummy data in this example).

Code:

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)

Expected result: If everything is set up correctly, you should see a new document appear in your MongoDB collection.

Conclusion

You set up MongoDB Data API and used a Raspberry Pi Pico W to connect to WiFi and insert a document into a MongoDB database. This is a clean starting point for IoT data logging, especially for slow-moving data that you want to store and query later.

Want the exact parts used in this build? Grab what you need from ShillehTek.com. If you want help customizing this project or building an IoT data pipeline for your product, check out our IoT consulting services.