Twitter (X) and MongoDB: store tweets as documents, upsert by id, query them fast

By TwitterAPI.io Team•13 min read
Pipeline diagram: read tweets from the API, upsert by tweet id into a MongoDB collection with indexes, react with a change stream
Twitter (X) to MongoDB in four steps. Figures from 1,660 posts collected in 2026.
TL;DR
  • Key on the tweet id. _id = tweet.id plus UpdateOne(upsert=True) makes every poll idempotent: in our re-poll test, 20 of 20 tweets on the second fetch were already stored.
  • A tweet is small for MongoDB. Median 6,989 bytes of BSON, p99 23,925, largest 63,101: 0.376% of the 16 MB cap.
  • Nested objects carry the weight. entities, author, retweeted_tweet, media and card hold 77.2% of the bytes; a slim projection drops 80.3%.
  • Three indexes cover the usual reads: {author.userName: 1, createdAt: -1}, one text index on text, and {conversationId: 1, createdAt: 1}.
  • Change streams need a replica set (or a sharded cluster / Atlas); resume with the stored token after a restart.
  • Cost: $0.15 per 1,000 tweets read here vs $5.00 per 1,000 post reads on the official X API rate card, about 33x; MongoDB storage is your own bill.

This page is about MongoDB specifically: one document per tweet, idempotent upserts, the indexes that serve timeline, keyword and thread queries, and change streams for alerts. If you want a serverless store with a live web page, the Firestore guide (scheduled Cloud Function, security rules) is the closer fit; if you want a spreadsheet-like base, see the Airtable guide. Both are linked below. Here the questions are document design and query shape.

Every number on this page comes from a small study we ran: 1,660 real posts from ten organization timelines and two keyword searches, collected in 2026, each encoded to BSON with the bson package that ships with PyMongo. We did not run a MongoDB server for the study, so the sizes are encoder output (the bytes a document occupies on the wire and before storage compression), not disk usage.

The code is Python with requests and pymongo. Reads need only an API key, no X developer account and no OAuth app.

Median size of a tweet stored in MongoDB as the API returns it (collected in 2026)

6,989 bytes of BSON; the largest of 1,660 posts was 63,101 bytes, 0.376% of the 16 MB limit

01 — Section

Step 1: why MongoDB fits Twitter (X) data, and the document shape to choose

An API response for a tweet is already a JSON object with nested parts: the author profile, entities (hashtags, URLs, mentions), extendedEntities.media with photo and video variants, an optional card, and whole embedded tweets in quoted_tweet or retweeted_tweet. A document store takes that object as-is. You can insert the first page in minutes and decide later which fields deserve an index, which is why tutorials on storing tweets in MongoDB have existed since the old streaming API.

The fit is good on size too. In our sample, 94.5% of tweets were under 16 KB of BSON and none reached 64 KB. MongoDB's limit is 16 MiB per document (mongodb.com/docs/manual/reference/limits/), so even the largest post we saw used 0.376% of it. Nesting is no issue either: the deepest tweet was 14 levels deep against a documented limit of 100.

Where it does not fit as well. Heavy joins across users, follower graphs and tweets read better in SQL, and columnar warehouses scan billions of rows more cheaply than a document store. If your end goal is a dashboard over months of history, BigQuery or Snowflake (guides linked below) may be the better landing zone, with MongoDB as the operational store in front of them.

Three jobs this page covers. Collect (poll a search or a timeline), store (one document per tweet, no duplicates, sortable dates), and use (indexes for the three common queries, plus a change stream that fires on every new tweet). The first decision is the document shape.

Use the tweet id as _id. The id is a numeric string ("1867..."); keep it a string. Numbers past 2^53 lose precision in JavaScript clients, and the API returns ids as strings anyway. With the id as primary key, MongoDB rejects a second insert of the same tweet and an upsert updates it in place.

Convert createdAt to a BSON Date. The API returns it as text in the form %a %b %d %H:%M:%S %z %Y (weekday, month, day, time, UTC offset, year). Stored as a string it sorts alphabetically, by weekday name first. Parse it once at write time; range queries, $dateTrunc and TTL-style cleanup all need a real date.

Embed the author, or reference it. Embedding keeps each tweet self-contained, which is what you want for alerts and exports. The cost is repetition: every tweet carries a full profile. We measured how much that costs in practice in the next sections; the short version is that for keyword searches it is a few percent of the collection, so embedding is a reasonable default.

Keep or drop the nested tweets. A retweet arrives with the original post inside retweeted_tweet, author and media included. That makes retweets the heaviest documents in organization timelines. If you only count retweets, keep the id and drop the body.

The shapes you can choose between:

ShapeWhat you storeGood forCost
Full documentThe API object as returned, _id = idArchives, re-processing laterMedian 6,989 B
Slim projectionText, counts, ids, author id and handle, URLsAnalytics, NLP, dashboardsMedian 702 B
Slim + users collectionSlim tweets plus one document per authorAccount tracking, profile historyOne upsert per author
02 — Section

Step 2: the collector, idempotent by tweet id

The script below reads newest-first pages from /twitter/tweet/advanced_search (queryType=Latest, 20 tweets a page, has_next_page and next_cursor for paging), converts dates, and writes each page with one bulk_write. Each operation is UpdateOne({_id: id}, {$set: tweet, $setOnInsert: {firstSeenAt}}, upsert=True).

Why $set and not insert. Like, repost, reply and view counts change after a tweet is published. An upsert refreshes them on every sighting, and firstSeenAt (written only on insert) still tells you when the tweet first reached your database.

Why ordered=False. MongoDB's bulkWrite docs say an ordered batch stops at the first error while an unordered one continues with the remaining operations. For a page of independent tweets that is what you want: one odd document should not drop the other nineteen. The driver also splits very large batches for you (the default maxWriteBatchSize is 100,000 operations).

When to stop paging. Latest results come newest-first, so the first page with zero new upserts means the rest is already stored. The script stops there, which keeps a frequent poll to a page or two. Page boundaries can shift between calls (see the re-poll test below), so pair the stop rule with a since_time: bound in the query and an occasional deeper sweep. We ran its to_document conversion on all 1,680 tweets fetched for this study (including the re-poll page) and encoded each result with bson.encode without an error; we did not run it against a live MongoDB server.

To follow accounts instead of a keyword, swap the endpoint for /twitter/user/last_tweets with userName=<handle> (tweets sit in data.tweets), or put several accounts in one search query as from:a OR from:b.

python
"""tweets_to_mongodb.py - pull posts for a search query from twitterapi.io and upsert them
into MongoDB, one document per tweet, keyed on the tweet id.

    pip install requests pymongo
    export TWITTERAPI_IO_API_KEY=...        # twitterapi.io dashboard
    export MONGODB_URI=mongodb://localhost:27017
    python tweets_to_mongodb.py "mongodb lang:en" 10
"""
import os
import sys
import time
from datetime import datetime, timezone

import requests
from pymongo import ASCENDING, DESCENDING, MongoClient, TEXT, UpdateOne

BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_API_KEY"]}
CREATED_FMT = "%a %b %d %H:%M:%S %z %Y"   # createdAt as the API returns it

db = MongoClient(os.environ.get("MONGODB_URI", "mongodb://localhost:27017"))["x"]
tweets = db["tweets"]


def ensure_indexes():
    # _id is the tweet id, so the primary key already dedupes. These serve the reads.
    tweets.create_index([("author.userName", ASCENDING), ("createdAt", DESCENDING)], name="author_time")
    tweets.create_index([("conversationId", ASCENDING), ("createdAt", ASCENDING)], name="thread")
    tweets.create_index([("text", TEXT)], name="text_search")


def to_document(t):
    doc = dict(t)
    tid = doc.pop("id")
    doc["createdAt"] = datetime.strptime(t["createdAt"], CREATED_FMT)   # BSON Date, sortable
    if doc.get("author", {}).get("createdAt"):
        doc["author"]["createdAt"] = datetime.strptime(doc["author"]["createdAt"], CREATED_FMT)
    return tid, doc


def upsert_page(page_tweets):
    now = datetime.now(timezone.utc)
    ops = []
    for t in page_tweets:
        tid, doc = to_document(t)
        ops.append(UpdateOne(
            {"_id": tid},
            {"$set": {**doc, "lastSeenAt": now}, "$setOnInsert": {"firstSeenAt": now}},
            upsert=True,
        ))
    if not ops:
        return 0, 0
    res = tweets.bulk_write(ops, ordered=False)
    return res.upserted_count, res.matched_count


def pull(query, max_pages=10):
    cursor, new_total = "", 0
    for page in range(max_pages):
        r = requests.get(
            f"{BASE}/twitter/tweet/advanced_search",
            headers=HEADERS,
            params={"query": query, "queryType": "Latest", "cursor": cursor},
            timeout=30,
        )
        r.raise_for_status()
        body = r.json()
        batch = body.get("tweets") or []
        new, seen = upsert_page(batch)
        new_total += new
        print(f"page {page + 1}: {len(batch)} tweets, {new} new, {seen} already stored")
        # Latest is newest-first: a page with nothing new means the rest is stored too.
        if new == 0 or not body.get("has_next_page"):
            break
        cursor = body.get("next_cursor") or ""
        time.sleep(1)   # fixed pacing; paid accounts can go faster
    return new_total


if __name__ == "__main__":
    q = sys.argv[1] if len(sys.argv) > 1 else "mongodb"
    pages = int(sys.argv[2]) if len(sys.argv) > 2 else 10
    ensure_indexes()
    print("new documents:", pull(q, pages))
    print("collection size:", tweets.estimated_document_count())
03 — Section

What the study measured: how big a tweet is in MongoDB

We encoded every tweet as a MongoDB document: the API object unchanged, with the id moved to _id. Across 1,660 posts the median was 6,989 bytes, the 90th percentile 14,888 and the 99th 23,925. JSON text of the same objects was close (median 7,331 bytes), so JSON size is a fair estimate when you have no encoder at hand.

SampleTweetsMedian BSONp90Largest
Organization timelines9606,710 B14,833 B63,101 B
Keyword searches7008,501 B14,888 B31,523 B
All1,6606,989 B14,888 B63,101 B

The distribution has two humps. Organization posts cluster at 4 to 6 KB; keyword-search posts split between small 2 to 4 KB documents and a large group at 12 to 16 KB, where nested entities are rich. Only 5.5% of all tweets passed 16 KB. At the mean size of 8,573 bytes, one GiB of uncompressed BSON holds about 125,243 full tweets; MongoDB's storage engine compresses on disk and indexes add their own space, so treat that as a planning figure, not a disk quote.

Histogram of tweet document sizes in KB of BSON for organization timelines and keyword searches
Full tweet document size, 1,660 posts collected in 2026. Sizes from bson.encode (PyMongo).
04 — Section

Where the bytes go, and what a slim projection saves

We split each document by top-level field. Across the whole sample, entities held 22.9% of the bytes, author 17.2%, retweeted_tweet 14.7%, extendedEntities (media) 11.7% and card 10.7%. The text, counts, ids and URLs that analysis usually reads were 18.7%.

The two samples differ in a useful way. In organization timelines, 31.6% of posts were retweets, and the embedded originals took 26.6% of the bytes. In keyword searches there were no retweets, but entities took 36.1%. Media was common in both: 52.2% and 56.6% of posts had at least one photo, video or GIF.

The slim projection in the code below keeps text, the six counts, createdAt, lang, conversationId, the author id and handle, hashtags, expanded URLs, media URLs and the ids of quoted or retweeted posts. It cut 80.3% of the bytes overall (91.9% for timelines, 66.2% for searches, where long-form posts keep their full text). Median slim size: 702 bytes, about 636,870 documents per GiB at the slim mean.

Pair the slim tweets with a users collection. Upsert one document per author keyed on the author id each time you see them. You keep follower counts and bios over time without copying the profile into every tweet.

python
def slim(t):
    """Keep what analysis reads; drop the bulky nested objects (about 80% of the bytes in our sample)."""
    a = t.get("author") or {}
    ents = t.get("entities") or {}
    media = (t.get("extendedEntities") or {}).get("media") or []
    return {
        "_id": t["id"], "text": t.get("text"), "createdAt": t.get("createdAt"), "lang": t.get("lang"),
        "likeCount": t.get("likeCount"), "retweetCount": t.get("retweetCount"),
        "replyCount": t.get("replyCount"), "quoteCount": t.get("quoteCount"),
        "viewCount": t.get("viewCount"), "bookmarkCount": t.get("bookmarkCount"),
        "conversationId": t.get("conversationId"), "isReply": t.get("isReply"),
        "author": {"id": a.get("id"), "userName": a.get("userName")},
        "hashtags": [h.get("text") for h in ents.get("hashtags") or []],
        "urls": [u.get("expanded_url") for u in ents.get("urls") or []],
        "media": [m.get("media_url_https") for m in media],
        "quotedId": (t.get("quoted_tweet") or {}).get("id"),
        "retweetedId": (t.get("retweeted_tweet") or {}).get("id"),
    }

def upsert_author(users, t, now):
    """users collection: one document per author, refreshed on every sighting."""
    a = dict(t.get("author") or {})
    if a.get("id"):
        users.update_one({"_id": a.pop("id")}, {"$set": {**a, "lastSeenAt": now}}, upsert=True)
Bar chart of the share of BSON bytes by tweet field for timelines and searches
Share of BSON bytes by top-level field, 1,660 posts collected in 2026.
05 — Section

Embedded authors and re-polls: how much duplication is real

Two duplication worries come up when people design this collection: the same author copied into many tweets, and the same tweet fetched again by the next poll. We measured both.

MeasureSearch: mongodbSearch: "tweets" database
Tweets300400
Distinct authors262233
Tweets per author1.151.72
Bytes spent repeating author objects3.2%4.7%

Authors. Keyword searches reach many different people, so repeated author objects cost only 3.2% to 4.7% of the collection. Embedding is fine there. The picture flips when you track a fixed set of accounts: each timeline document repeats the same profile, and a slim tweet plus a users collection removes nearly all of that.

Re-polls. We fetched page 1 of the mongodb Latest search again about three minutes after the first pull. All 20 of the 20 tweets on that page were already stored and 0 were new. Only 4 of them had been on the first pull's page 1, so page boundaries shifted between calls even with nothing new published. That is the case for deduplicating on the tweet id rather than on page position or a saved cursor, and it is exactly what an _id upsert gives you for free.

Cut the re-reads too. Dedupe protects the database; it does not stop you paying for the same tweets again. Add a time bound to the query (since_time:<unix seconds> from your newest stored createdAt) or stop at the first page with no new upserts, as the collector does.

06 — Section

Step 3: indexes for the three common queries

Every collection already has the _id index, which serves lookups by tweet id and the upserts. Add an index per query shape you actually run; MongoDB allows up to 64 indexes per collection and 32 fields in a compound index (mongodb.com/docs/manual/reference/limits/).

QueryIndexNotes
One account, newest first{author.userName: 1, createdAt: -1}Equality first, then the sort field
Keyword in stored text{text: "text"}One text index per collection
A whole thread in order{conversationId: 1, createdAt: 1}Rebuild replies from stored tweets
Recent window, any author{createdAt: -1}Only if you query by time alone

About the text index. MongoDB's docs say a collection can have only one text index (it may cover several fields), that text indexes can use significant RAM and slow writes, and that MongoDB recommends its MongoDB Search indexes instead of text indexes. On Atlas, use MongoDB Search for real full-text needs; on a self-managed server the text index is the built-in option. The match is on stemmed words, so a search for atlas matches the word, not a substring.

Check the plan. Call .explain() on each query and confirm the winning plan uses IXSCAN on the index you expected rather than a COLLSCAN. We did not run a server for this study, so we make no claim here about query timings; measure them on your own data.

python
from datetime import datetime, timedelta, timezone

# 1) one account, newest first  -> served by author_time
list(tweets.find({"author.userName": "MongoDB"}).sort("createdAt", -1).limit(50))

# 2) keyword inside the stored text -> served by the text index
list(tweets.find({"$text": {"$search": "atlas"}}, {"score": {"$meta": "textScore"}})
     .sort([("score", {"$meta": "textScore"})]).limit(20))

# 3) a whole thread in order -> served by thread
list(tweets.find({"conversationId": "<conversation id>"}).sort("createdAt", 1))

# check which index a query used
tweets.find({"author.userName": "MongoDB"}).sort("createdAt", -1).explain()["queryPlanner"]["winningPlan"]

# daily volume per author for the last 7 days
since = datetime.now(timezone.utc) - timedelta(days=7)
list(tweets.aggregate([
    {"$match": {"createdAt": {"$gte": since}}},
    {"$group": {"_id": {"user": "$author.userName",
                        "day": {"$dateTrunc": {"date": "$createdAt", "unit": "day"}}},
                "posts": {"$sum": 1}, "likes": {"$sum": "$likeCount"}}},
    {"$sort": {"_id.day": -1, "posts": -1}},
]))
07 — Section

Step 4: alerts with a change stream

Once the collector writes to MongoDB, anything downstream can react to the writes instead of polling the database. A change stream is a cursor that yields an event for each insert, update or delete on a collection. Filter it to inserts and you have a feed of tweets that are new to you, whatever process wrote them.

It needs a replica set. MongoDB's docs state change streams are available for replica sets and sharded clusters (WiredTiger, protocol version 1). A standalone server is not on that list, so for local development start mongod as a single-node replica set. Atlas clusters are replica sets, so they work out of the box.

Make it restartable. Each event carries a resume token. Save it after handling the event and pass it back as resume_after on restart; the docs note that the oplog must still hold the operation the token points to, and that you should reopen the stream with the same pipeline and options. Use start_after instead if the stream was closed by an invalidate event such as a collection drop.

Inserts only. The collector's upserts also fire update events every time counts refresh. Matching operationType: insert keeps the alert to the first sighting of each tweet.

python
"""alerts_from_change_stream.py - react to every tweet the poller inserts.
Change streams need a replica set or a sharded cluster (an Atlas cluster qualifies)."""
import json
import os
from pathlib import Path

from pymongo import MongoClient

tweets = MongoClient(os.environ["MONGODB_URI"])["x"]["tweets"]
TOKEN_FILE = Path("resume_token.json")
pipeline = [
    {"$match": {"operationType": "insert"}},
    {"$project": {"fullDocument._id": 1, "fullDocument.text": 1,
                  "fullDocument.author.userName": 1, "fullDocument.createdAt": 1}},
]
resume = json.loads(TOKEN_FILE.read_text()) if TOKEN_FILE.exists() else None

with tweets.watch(pipeline, resume_after=resume) as stream:
    for change in stream:
        doc = change["fullDocument"]
        print("new tweet", doc["_id"], "by", doc["author"]["userName"])
        # hand off to Slack, a queue, an email job ...
        TOKEN_FILE.write_text(json.dumps(stream.resume_token))
08 — Section

What it costs to fill the collection, vs the official X API

MongoDB storage is your own bill (Atlas tier or your server). The read side is per tweet. On TwitterAPI.io, tweet endpoints cost 15 credits per tweet returned, $0.15 per 1,000 tweets, with a minimum of 15 credits ($0.00015) per request, so a full 20-tweet page costs $0.003. The official X API pay-per-usage rate card (docs.x.com/x-api/getting-started/pricing) lists $0.005 per post read, $5.00 per 1,000, about 33x more, and caps pay-per-usage at 3 million post reads a month before Enterprise.

Tweets storedTwitterAPI.ioOfficial X API (pay-per-usage)
10,000$1.50$50
100,000$15$500
1,000,000$150$5,000

Polling floor. A poll that finds nothing still costs the $0.00015 minimum. Every 60 seconds for a month that is 43,200 checks, $6.48; every 5 minutes, $1.30. Our re-poll found 0 new tweets in three minutes on a niche keyword, so match the interval to how busy the query is.

Throughput. Accounts run at 0.2 requests per second before the first payment and 20 once paid (50 on Scale, 500 on Business), which bounds how fast a backfill can page. New accounts that pass the automatic bot check get free starter credits (no card, one per person or network, expiring after 31 days); see the pricing page for the current amount.

This study's own bill. 86 requests returned 1,680 tweets (including the re-poll page), about $0.25 at $0.15 per 1,000.

09 — Section

How we collected this

Question. How large is a tweet stored as a MongoDB document, which fields carry the bytes, how much does embedding the author repeat, and how many tweets does a second poll return that are already stored?

Accounts and queries. Timelines (/twitter/user/last_tweets, up to 5 pages each) of ten organization accounts: MongoDB, vercel, github, Docker, nvidia, NASA, OpenAIDevs, CloudflareDev, PlayStation and Xbox. Two Latest searches (/twitter/tweet/advanced_search): mongodb and "tweets" database, up to 20 pages each, plus one re-poll of page 1 of the first search about three minutes later.

Sample and window. 1,660 posts (960 from timelines, 700 from searches), 86 requests, collected in 2026; each account's window is its recent posts at collection time.

Method. Each tweet was encoded with bson.encode (pymongo 4.18.3) after moving id to _id; part sizes are the encoded size of each top-level field. No MongoDB server was run, so there are no disk, compression or query-time figures here.

What the sample cannot show. Ten organization accounts and two queries are not all of X: accounts that post long-form articles, video threads or heavy quote chains will skew larger. The re-poll result is a single test on one quiet keyword; a busy query would return new tweets in the same interval.

Privacy. Aggregates only. Raw organization timelines are kept compressed for reproducibility; raw search pages, which are mostly from private individuals, were not kept, and the de-identified rows carry no ids, URLs, text or handles.

python
"""tweets_to_mongodb.py - pull posts for a search query from twitterapi.io and upsert them
into MongoDB, one document per tweet, keyed on the tweet id.

    pip install requests pymongo
    export TWITTERAPI_IO_API_KEY=...        # twitterapi.io dashboard
    export MONGODB_URI=mongodb://localhost:27017
    python tweets_to_mongodb.py "mongodb lang:en" 10
"""
import os
import sys
import time
from datetime import datetime, timezone

import requests
from pymongo import ASCENDING, DESCENDING, MongoClient, TEXT, UpdateOne

BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_API_KEY"]}
CREATED_FMT = "%a %b %d %H:%M:%S %z %Y"   # createdAt as the API returns it

db = MongoClient(os.environ.get("MONGODB_URI", "mongodb://localhost:27017"))["x"]
tweets = db["tweets"]


def ensure_indexes():
    # _id is the tweet id, so the primary key already dedupes. These serve the reads.
    tweets.create_index([("author.userName", ASCENDING), ("createdAt", DESCENDING)], name="author_time")
    tweets.create_index([("conversationId", ASCENDING), ("createdAt", ASCENDING)], name="thread")
    tweets.create_index([("text", TEXT)], name="text_search")


def to_document(t):
    doc = dict(t)
    tid = doc.pop("id")
    doc["createdAt"] = datetime.strptime(t["createdAt"], CREATED_FMT)   # BSON Date, sortable
    if doc.get("author", {}).get("createdAt"):
        doc["author"]["createdAt"] = datetime.strptime(doc["author"]["createdAt"], CREATED_FMT)
    return tid, doc


def upsert_page(page_tweets):
    now = datetime.now(timezone.utc)
    ops = []
    for t in page_tweets:
        tid, doc = to_document(t)
        ops.append(UpdateOne(
            {"_id": tid},
            {"$set": {**doc, "lastSeenAt": now}, "$setOnInsert": {"firstSeenAt": now}},
            upsert=True,
        ))
    if not ops:
        return 0, 0
    res = tweets.bulk_write(ops, ordered=False)
    return res.upserted_count, res.matched_count


def pull(query, max_pages=10):
    cursor, new_total = "", 0
    for page in range(max_pages):
        r = requests.get(
            f"{BASE}/twitter/tweet/advanced_search",
            headers=HEADERS,
            params={"query": query, "queryType": "Latest", "cursor": cursor},
            timeout=30,
        )
        r.raise_for_status()
        body = r.json()
        batch = body.get("tweets") or []
        new, seen = upsert_page(batch)
        new_total += new
        print(f"page {page + 1}: {len(batch)} tweets, {new} new, {seen} already stored")
        # Latest is newest-first: a page with nothing new means the rest is stored too.
        if new == 0 or not body.get("has_next_page"):
            break
        cursor = body.get("next_cursor") or ""
        time.sleep(1)   # fixed pacing; paid accounts can go faster
    return new_total


if __name__ == "__main__":
    q = sys.argv[1] if len(sys.argv) > 1 else "mongodb"
    pages = int(sys.argv[2]) if len(sys.argv) > 2 else 10
    ensure_indexes()
    print("new documents:", pull(q, pages))
    print("collection size:", tweets.estimated_document_count())

Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.

10 — Questions

Questions readers ask

Can I insert the Twitter API JSON straight into MongoDB?

Yes. Each tweet object becomes a document; move id to _id so duplicates are impossible, and convert createdAt (text in the form %a %b %d %H:%M:%S %z %Y) to a datetime so it sorts and filters as a date. Field names in the API response contain no dots or leading dollar signs, so no renaming is needed.

Will a tweet ever hit MongoDB's 16 MB document limit?

Not in our sample. The largest of 1,660 posts was 63,101 bytes of BSON, 0.376% of the 16 MiB limit, and none passed 64 KB. The limit matters only if you append replies or history into one growing document, which is a reason to store one document per tweet.

How do I avoid duplicate tweets when I poll every minute?

Use the tweet id as _id and write with UpdateOne(..., upsert=True). Re-fetched tweets update in place. In our test, all 20 tweets on a page fetched again three minutes later were already stored. Also add since_time: to the query or stop at the first page with no new upserts, so you do not pay to read the same tweets.

Should I embed the author or store users separately?

For keyword searches, embedding is fine: repeated author objects cost 3.2% to 4.7% of the collection in our sample. For a fixed list of accounts, store a slim tweet with the author id and handle, and keep one users document per author.

Which index do I need to search tweet text in MongoDB?

A text index on text supports $text queries; a collection can have only one text index. MongoDB's docs recommend MongoDB Search indexes over text indexes, so on Atlas use MongoDB Search for serious full-text work.

Why does watch() fail on my local MongoDB?

Change streams are available for replica sets and sharded clusters, not a standalone server. Start mongod as a single-node replica set for development, or use an Atlas cluster.

Do I need an X developer account to collect the tweets?

Not with TwitterAPI.io: reads use one API key in the X-API-Key header, no X account or OAuth app. Tweet reads cost $0.15 per 1,000 tweets, compared with $0.005 per post read on the official X API pay-per-usage rate card.

11 — Further reading

Continue

Sources & further reading
More from this series

Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.

Build it

Stop reading. Start building.

Starter credits cover real testing on real data. Google sign-in, no card, no application queue.

Get an API key

Already building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.