You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python Flask中从MongoDB mLab获取键含指定关键词的文档

Solution: Fetch MongoDB Documents with Keyword Matching in Flask

First, let's break down what you need: creating a Flask endpoint that connects to your mLab-hosted MongoDB database and returns documents where a specific field (like brand_name in your example) contains a given keyword. Here's a step-by-step implementation tailored to your use case:

Prerequisites

First, install the required packages:

pip install flask pymongo

Full Implementation Code

Replace the placeholder values with your actual mLab database credentials and collection name:

from flask import Flask, jsonify
from pymongo import MongoClient

# Initialize Flask app
app = Flask(__name__)

# Connect to your mLab MongoDB database
# Grab your connection string directly from your mLab dashboard (includes username/password)
client = MongoClient('mongodb://your_username:your_password@dsxxxx.mlab.com:xxxx/your_database_name')
db = client.get_database()
collection = db.your_collection_name  # e.g., db.brands if your collection is named 'brands'

@app.route('/documents/<keyword>', methods=['GET'])
def fetch_documents(keyword):
    # Query to find documents where 'brand_name' contains the keyword (case-sensitive)
    # Uncomment the '$options' line below for case-insensitive matching
    query = {
        'brand_name': {
            '$regex': keyword,
            # '$options': 'i'
        }
    }
    
    # Execute the query and convert results to a list
    matching_docs = list(collection.find(query))
    
    # Convert MongoDB's ObjectId to string (JSON can't serialize ObjectId directly)
    for doc in matching_docs:
        doc['_id'] = str(doc['_id'])
    
    # Return results as valid JSON
    return jsonify(matching_docs)

if __name__ == '__main__':
    app.run(debug=True)

Key Details Explained

  1. MongoDB Connection: The MongoClient uses your mLab connection string, which you can copy directly from your mLab database dashboard (it includes all necessary credentials and host info).
  2. Regex Query: We use MongoDB's $regex operator to match documents where the brand_name field contains your target keyword. By default, this is case-sensitive—uncomment the $options: 'i' line if you want to ignore case.
  3. JSON Serialization: MongoDB's _id is an ObjectId type, which can't be serialized to JSON. We convert it to a string to ensure the response is valid.
  4. Testing the Endpoint: Run the Flask app, then visit http://localhost:5000/documents/MAZ in your browser or a tool like Postman. This will return the first two documents from your example, since their brand_name contains "MAZ".

Matching Any Field (Optional)

If you want to find documents where any field contains the keyword (not just brand_name), use a $or query to check all relevant fields:

query = {
    '$or': [
        {'brand_name': {'$regex': keyword}},
        {'name': {'$regex': keyword}}
        # Add more fields here if needed
    ]
}

Production Notes

  • Disable debug mode (debug=False) when deploying to production.
  • Store your database credentials in environment variables instead of hardcoding them for security.
  • mLab is now integrated with MongoDB Atlas, so your connection string might look slightly different if you've migrated, but the pymongo setup remains identical.

内容的提问来源于stack exchange,提问作者Pyd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:01:25