Web Scraping & Bots · 课时

将数据存储在 NoSQL 数据库中

学习何时以及如何将抓取的数据持久化到 MongoDB 等面向文档的 NoSQL 存储中,以实现灵活且弱模式约束的存储。

第 4 / 4 课13 个步骤

将数据存储在 NoSQL 数据库中 是 CoddyKit 上的免费 Web Scraping & Bots 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Web Scraping & Bots 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Web Scraping & Bots 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

When SQL Is Not Enough

Scraped data is often irregular: different pages yield different fields, nested structures, and evolving shapes. Rigid SQL schemas can be painful here.

NoSQL document databases store flexible JSON-like records, making them a natural fit for messy web data.

Documents and Collections

In a document store like MongoDB:

  • A document is one JSON-like record.
  • A collection groups related documents (like a table).
  • Documents in one collection need not share the same fields.
{
  "title": "Widget",
  "price": 9.99,
  "tags": ["tools", "sale"],
  "vendor": { "name": "Acme", "rating": 4.5 }
}

Connecting with PyMongo

The pymongo driver connects Python to MongoDB. Grab a database and a collection handle to start writing.

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017')
db = client['scraping']
products = db['products']

Inserting Documents

Insert a single scraped record with insert_one or a batch with insert_many. MongoDB assigns an _id automatically.

record = {'title': 'Gadget', 'price': 14.5, 'tags': ['new']}
result = products.insert_one(record)
print(result.inserted_id)

Avoiding Duplicates with Upsert

Re-running a scraper should not create duplicate rows. An upsert updates the matching document or inserts it if absent, keyed by a stable field like the product URL.

products.update_one(
    {'url': record['url']},
    {'$set': record},
    upsert=True
)

Unique Indexes

Enforce uniqueness at the database level with an index. This protects integrity even if your code has a bug.

products.create_index('url', unique=True)

Querying Stored Data

Retrieve records with filter documents. Operators like $gt and $in express conditions.

cheap = products.find({'price': {'$lt': 10}})
for doc in cheap:
    print(doc['title'], doc['price'])

Storing Nested and Array Data

Unlike flat SQL columns, documents keep nested objects and arrays natively. This preserves the original structure of scraped pages without join tables.

review_doc = {
  'product': 'Widget',
  'reviews': [
    {'user': 'a', 'stars': 5},
    {'user': 'b', 'stars': 4}
  ]
}
db['catalog'].insert_one(review_doc)

Bulk Writes for Speed

For large scrapes, batch operations dramatically reduce round trips. Collect writes and flush them together.

from pymongo import UpdateOne

ops = [UpdateOne({'url': r['url']}, {'$set': r}, upsert=True) for r in batch]
products.bulk_write(ops)

SQL vs NoSQL for Scraping

Choose based on your data:

  • NoSQL for variable, nested, fast-changing records.
  • SQL when fields are stable and you need joins or strict constraints.

Many pipelines stage raw data in NoSQL, then transform into SQL for analysis.

Adding Timestamps and Metadata

Always stamp each scraped document with when it was captured and its source. This lets you track freshness, debug bad runs, and re-scrape stale records selectively.

from datetime import datetime

record['scraped_at'] = datetime.utcnow()
record['source'] = 'site.com'
products.insert_one(record)

Quick Check

Test your understanding of NoSQL storage.

Recap

You learned to persist scraped data in NoSQL: documents and collections, connecting with PyMongo, upserts and unique indexes to prevent duplicates, querying, nested data, and bulk writes.

Document stores give scrapers flexible, scalable persistence.

免费开始

用 AI 导师学习 Python — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
12
课程
48

常见问题解答

「将数据存储在 NoSQL 数据库中」课时是免费的吗?

是的 — 「将数据存储在 NoSQL 数据库中」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web Scraping & Bots 课程的其余内容,请升级到 CoddyKit PRO。 Web Scraping & Bots 课程共包含 4 节课。

「将数据存储在 NoSQL 数据库中」这节课中我会学到什么?

学习何时以及如何将抓取的数据持久化到 MongoDB 等面向文档的 NoSQL 存储中,以实现灵活且弱模式约束的存储。 你通过在浏览器中直接运行的动手代码来练习 Web Scraping & Bots,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Web Scraping & Bots 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Web Scraping & Bots 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「将数据存储在 NoSQL 数据库中」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Web Scraping & Bots 课中编写并运行代码吗?

能。每节 Web Scraping & Bots 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 将数据存储为 CSV/JSON
  2. 与数据库集成(SQL)
  3. 云存储方案
  4. 将数据存储在 NoSQL 数据库中
← 返回 Web Scraping & Bots