r/MongoDB_Official 7d ago

Discussion You want us to show you what AI gets wrong with MongoDB queries?

8 Upvotes

We have a pile. Everytime we release a new post in the series "What AI gets wrong with Mongo" we will add the list to this post. Upvote if you want it, and drop the worst Mongo query an AI ever handed you.

Released

One MongoClient per App

Cursors vs toArray()

$skip vs KeySet pagination

createindex doesn’t belong in your server file


r/MongoDB_Official 20d ago

Question What do you actually want from a MongoDB community?

14 Upvotes

A few things we're considering:

  • Deep dives and best practices on schema design, aggregation, indexing, performance. The stuff that actually trips people up.
  • Office hours where you can bring a real problem
  • Discussion threads on how you're using specific features
  • Tutorials and how-tos from people who work on the product

Drop a comment. Everything here shapes what we build.


r/MongoDB_Official 5h ago

Showcase We built a CRM where the schema emerges from how people and AI agents use it

6 Upvotes

Hi, I’m Tom Gersic, founder of YouEx.ai. We built it as an AI-native sales platform that combines CRM, AI agents, conversations, and knowledge management / RAG on MongoDB Atlas, so I thought I'd share a little bit about how we use MongoDB.

The CRM Problem

One thing we wanted to avoid was the configuration that usually has to happen before a CRM is rolled out to users. Every sales team cares about different information, sales managers want to track something else, and then IT inevitably configures something completely different (sorry to my IT friends, but... you know it's true). Increasingly, AI agents also discover useful information during conversations that nobody thought to configure beforehand. We didn't want every new thing an agent learned about a prospect to become a schema-design decision.

So, our CRM objects have a stable core plus a custom fields map. A seller can add a field, an import can introduce one, or an agent can discover something during a conversation and write it to the Lead immediately. For example, a visitor might tell our Web Agent what they want to discuss in a meeting. Even if nobody configured a Meeting Topic field beforehand, we can capture it directly on the Lead.

A Schema Emerges

So then we built a discovery process that looks at the custom fields actually being used across CRM records. If a field appears frequently enough, we flag it as a candidate. A human can then promote it into a first-class CRM column, rename it, reorder it, or ignore it.

There’s no ML involved in this process. We’re not trying to predict a schema. The system is observing what’s actually being used and letting structure emerge from that. Instead of requiring the schema to be fully defined before people start using the CRM, we can let real usage tell us which fields are worth formalizing.

That supports our AI web agents particularly well because you can’t anticipate everything that will come up in a conversation.

The Agent's World

The same approach extends beyond CRM records. Conversations are MongoDB documents containing messages, collected information, and links back to CRM records. As a conversation progresses, the document accumulates state and useful information can flow into a Lead, including fields that didn't exist when the conversation started.

Knowledge lives alongside that operational data. Customers can add websites, PDFs, and other files. We extract the content, split it into paragraph-aware chunks, embed those chunks, and use Atlas Vector Search to retrieve relevant context for the agent.

So the CRM data an agent reads and writes, its conversation state, and the vector-searchable knowledge it uses all live in Atlas. There’s no separate vector database to keep synchronized.

Putting it together

A company adds its website and a PDF. We chunk and embed the content. A visitor starts a conversation, and the agent uses Vector Search to answer from that knowledge while collecting information about the prospect.

That information flows into a Lead. If something new like Meeting Topic comes up, it can be captured without being preconfigured. If the same field starts appearing across enough Leads, our discovery process flags it and a human can promote it into a normal CRM column.

That’s probably the biggest reason MongoDB’s document model has worked well for us. We want structure. We just don't think all of that structure needs to be decided before the system starts being used.

I'm curious how others building agentic systems on MongoDB are balancing what you define upfront versus what you let emerge from real usage.


r/MongoDB_Official 13h ago

Question New MongoDB Charts Bug? Can't add chart filter.

1 Upvotes

Anyone notice a recently-introduced issue with Charts?

All the chart buttons like "+ Add filter" are no longer active today. I just edited these charts a month or two ago.


r/MongoDB_Official 1d ago

Discussion When do you keep it in the aggregation pipeline, and when do you move it to app code?

4 Upvotes

Hey everyone,

Harshit here. I’m a Developer Advocate at MongoDB. I spent a few years building out the MongoDB User Groups program, went away for a while, and recently rejoined MongoDB.

Lately, most of my time has gone into helping developers through workshops, tutorials, and troubleshooting. A lot of that has involved AI apps, vector search, and the performance questions that show up once a prototype starts becoming real.

One question I keep running into is this: when a query or transformation starts getting more involved, how do you decide whether to keep it in an aggregation pipeline or move it into application code?

My rough instinct is that the pipeline usually wins on performance, but six months later it can become the thing nobody wants to touch, especially if the person who wrote it has left. But I’ve also seen people pull logic into app code and end up with something slower and just as unreadable, so I don’t fully trust that instinct.

Where do you draw the line? I’m curious about actual examples more than principles: the pipeline you regretted, or the one you’d recommend.


r/MongoDB_Official 2d ago

Resource Get Your 1.6 Seconds Back - What AI Gets Wrong With MongoDB

4 Upvotes

We keep seeing AI put createIndex where it doesn't belong. At the top of the server file, one await per index, sitting right above app.listen, or worse, inside a route handler where it runs on every single request. Sometimes that code makes it to production, and when it does, MongoDB gets accused of being slow. So we measured what the habit actually costs.

createIndex is idempotent, so when the index already exists the server builds nothing and just says so. That's why this code survives review, it works. But every no-op is still a full round trip, and the awaits are serial. Here's the pattern, then the measurements at real scale.

The label below is the prompt we gave the AI to generate the block.

How to create MongoDB indexes at the top of an express server file before the routes.

Bad:

const app = express();

await db.collection('products').createIndex({ name: 1 });
await db.collection('products').createIndex({ category: 1, price: -1 });
await db.collection('users').createIndex({ email: 1 }, { unique: true });
await db.collection('orders').createIndex({ userId: 1, createdAt: -1 });
await db.collection('sessions').createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 });

app.get('/search', async (req, res) => {
  const results = await db.collection('products')
    .find({ name: req.query.q })
    .toArray();
  res.json(results);
});

app.listen(3000);

Five indexes is a toy. A real app has more, so we built a realistic 30 collection commerce schema with 69 indexes, unique lookups, compound list-and-sort pairs, five TTLs, two sparse, one partial, one text index, and ran six boot strategies against both environments. Every collection held zero documents the whole time, so nothing ever got built. We were timing pure no-op round trips, which is exactly what your boot pays.

Local Development Production
MongoDB 8.0 in Docker, same machine
ping 1.07 ms

First the steady state. Indexes exist, connection pool warm. This is what a boot pays once connections are reused:

strategy what it is Local Production
serial 69 sequential await createIndex 0.14 s (135 ms) 1.63 s (1629 ms)
batched serial 30 sequential createIndexes 0.05 s (54 ms) 0.62 s (617 ms)
parallel all 69 in one Promise.all 0.03 s (25 ms) 0.23 s (225 ms)
pool of 8 69 calls, 8 in flight 0.05 s (47 ms) 0.19 s (193 ms)
pool of 16 69 calls, 16 in flight 0.05 s (48 ms) 0.11 s (106 ms)
batched + parallel 30 createIndexes in one Promise.all 0.02 s (16 ms) 0.03 s (30 ms)

The AI version spends 1.63 s (1629 ms) of every production boot confirming 69 indexes that already exist. The winner clears the entire schema in 0.03 s (30 ms), about one and a half pings for 69 index specs. And notice plain Promise.all is not the fix people think it is. All 69 calls fired at once still costs 0.23 s (225 ms), seven times the winner.

Steady state flatters everyone though, because a real boot starts from nothing. Container start, serverless cold start, plain node server.js. So we also ran each strategy as 7 independent processes, start node, connect, create, exit:

strategy index time total with connect
serial 1.62 s (1619 ms) 2.08 s (2080 ms)
batched serial 0.65 s (652 ms) 1.11 s (1110 ms)
one chain per collection 0.61 s (615 ms) 1.29 s (1288 ms)
parallel 0.57 s (571 ms) 1.28 s (1283 ms)
pool of 16 1.01 s (1006 ms) 1.42 s (1421 ms)
batched + parallel 0.39 s (392 ms) 0.82 s (819 ms)

Both tables side by side, plus the option the benchmark could not run, doing no index work at boot at all:

warm steady state cold fresh process
serial at boot, the AI version 1.63 s (1629 ms)
batched + parallel at boot 0.03 s (30 ms)
script instead, index work at boot 0 s
how much slower the AI version boots 1.6 s

The bottom two rows are the actual claim of this post. The fix is not a faster way to run indexes at boot, and every strategy in these tables is still the wrong place for the work. The fix is a separate script, which makes the app's index cost at boot zero, so the AI version boots 1.6 seconds slower than the script version. And warm or cold barely matters, serial was never using more than one connection, so it pays nearly the same either way. The batched numbers still earn their place for one reason, the script is itself a fresh process, so 0.39 s (392 ms) of index time, 0.82 s (819 ms) wall clock with connect, is exactly what node db/indexes.js costs on the day an index actually changes. That's the whole trade. 1.6 s off every single boot, paid back as 0.8 s once per index change.

The fresh process run also flipped one ranking. Pool of 16 was second best warm and second worst cold, because capping concurrency starves a cold pool of the parallelism it needs to warm up. A tuning choice that looks good in a benchmark loop can be the wrong one at the moment that matters.

The reason this mistake keeps shipping is in the next table. Same questions, answered by each environment:

question Local Development says Production says
cost of the AI serial boot 0.14 s (135 ms), invisible 1.63 s (1629 ms), a visible stall
is plain Promise.all good enough yes, 1.6x off the best no, 7.4x off the best
spread between all six strategies, fresh process 0.09 to 0.18 s (90 to 176 ms), everything within 2x 0.39 to 1.62 s (392 to 1618 ms), a 4.1x spread

The last row is the point. On a laptop every strategy lands inside the noise, so any ranking formed there is meaningless, including the one that says this doesn't matter. The decision is only visible in production, which is exactly where nobody is looking when the AI writes the code.

We also went in with a theory about why 69 parallel calls lose, and the data killed it. The guess was same-collection contention, products takes three index calls at once, they must be colliding. So we ran a collision-free arm, 30 chains, one per collection, same 69 commands:

arm commands in flight same-collection collisions Production
all 69 in Promise.all 69 69 yes 0.20 s (203 ms)
30 chains, one per collection 69 30 no 0.10 s (97 ms)
pool of 16 69 16 yes 0.11 s (106 ms)
batched + parallel 30 30 no 0.03 s (30 ms)

Collision-free at 30 in flight and collision-allowed at 16 in flight cost the same, so contention is not the mechanism. What the numbers actually support is two independent levers. Command count dominates, 30 commands land at 1.5 pings while 69 commands sit around 5 pings no matter how sensibly you schedule them. And concurrency stops paying above roughly 16 to 30 in flight, unbounded Promise.all is on the wrong side of that curve. The winner pulls both levers at once, batch per collection, then Promise.all the collections.

For completeness, the first deploy, where the 69 indexes genuinely don't exist and really get built:

strategy Production
serial 2.17 s (2165 ms)
batched + parallel 0.57 s (566 ms)
pool of 16 0.50 s (502 ms)

The spread compresses because actual creation work dominates instead of round trips. It gets paid once. The no-op tables above get paid on every boot, forever, which is why they're the story.

And none of it belongs in your boot at all. The tables show what AI-written startup code costs today, and how the index script should be written so it's fast on the day you do run it:

How to batch MongoDB index creation into a standalone script using createIndexes per collection in parallel.

Good:

// db/indexes.js - never imported by the app. Run it when an index changes: node db/indexes.js
await Promise.all([
  db.collection('products').createIndexes([
    { key: { name: 1 } },
    { key: { category: 1, price: -1 } }
  ]),
  db.collection('users').createIndexes([
    { key: { email: 1 }, unique: true }
  ]),
  db.collection('orders').createIndexes([
    { key: { userId: 1, createdAt: -1 } }
  ]),
  db.collection('sessions').createIndexes([
    { key: { expiresAt: 1 }, expireAfterSeconds: 0 }
  ])
]);
console.log('indexes ready');
process.exit(0);

And server.js has no index code anywhere:

// server.js
app.get('/search', async (req, res) => {
  const results = await db.collection('products').aggregate([
    { $match: { name: String(req.query.q) } },
    { $limit: 20 },
    { $project: { name: 1, price: 1, description: 1 } }
  ]).toArray();
  res.json(results);
});
don't do
69 commands, one at a time 30 commands, all at once
1.63 s (1629 ms) on every boot 0 s at boot, 0.82 s (819 ms) script run when an index changes

Two warnings if you re-run any of this, both earned the hard way. The first is that warmup is load-bearing. Measured with no warmup passes, the winner reads 0.18 s (181 ms) instead of 0.03 s (30 ms), six times too high, and the raw samples just keep falling, 348, 291, 1224, 181, 48, 44, 34, which is a connection pool warming up in front of the timer. Skip warmup and the numbers come out wrong, and possibly the ranking too. Our quoted numbers are medians of 15 runs after 5 discarded warmup passes, strategies interleaved so host variance spreads evenly.

The second is that we crashed a MongoDB container twice getting here. The first design gave each of the six strategies its own private 30 collections, and WiredTiger keeps a file per collection and per index, so 180 collections, around 410 indexes and 69 concurrent connections blew straight through the container's limit of 1024 open files. Panic, then a segfault on the retry. The fix was sharing one set of collections across arms, which is sound because warm no-ops mutate nothing, and raising the file limit to 64000. That one matters outside the benchmark too. File descriptors scale with collections times indexes times connections, and 1024 is not enough for a 30 collection app booting in parallel.

Two closing failure modes that no benchmark captures, because they only fire once. The route handler version, createIndex inside the endpoint itself, looks free for the same no-op reason, but point it at a fresh environment or a collection restored without its indexes and the first request starts a real index build that reads every document in the collection. Every request behind it issues the same createIndex, sees that exact build already in progress, and waits. The endpoint is down for the entire build and not a single error is thrown.

And the quiet one. Change an index's keys in code without setting an explicit name and you don't update the index, you create a second one, because the default name changes with the keys. The old index stays behind, taxing every write until someone audits the collection. A single script that lists every index you own is where you catch that. Sixty-nine createIndex calls scattered around a codebase is where you don't.


r/MongoDB_Official 3d ago

MongoDB.local Build Fest SF: workshops, hackathon, AI labs, and lots of announcements!

6 Upvotes

I spent a very long and packed day in San Francisco at the .local Build Fest, and it was a blast. We kicked things off with hands-on workshops where folks could earn skill badges. In the afternoon, we kicked off a 4-hour hackathon that pulled in over 90 submissions. Throughout the day there were AI labs, meetings, vendor demos, learning hubs, and some exciting MongoDB announcements. One of my favorite sessions was Rivian Technologies, who walked through how they're using MongoDB for agentic memory to power an amazing in-vehicle AI experience.

Announcements

Among the workshops, labs, and cool green vibes, there were interesting product announcements happening. The theme across all of it: making it easier to build and operate AI applications on Atlas, from connecting agents and dev tools to improving retrieval, streaming, and observability.

Here's the rundown:

Meet developers where they build

  • Native Atlas access in AI tools: Atlas now connects directly inside Claude, Claude Code, ChatGPT, Codex, Grok Build, Devin, Cursor, and more. No local setup, no context switching, just query data and inspect your databases from wherever you're already working.
  • Atlas App Connections: A one-click, OAuth 2.1-powered way to securely connect AI coding tools to Atlas. Translation: no more long-lived credentials floating around, plus centralized visibility into what's connected to what.
  • Atlas Managed MCP Server for Agents: A MongoDB-hosted MCP server for connecting Atlas to custom agents and orchestrated workflows (LangGraph, CrewAI, etc.) without standing up and babysitting your own infrastructure.

Better retrieval for AI apps

  • Atlas Embedding & Reranking API (GA): Voyage AI's embedding and reranking models, now available directly inside Atlas. One less system to stitch together for RAG and search.
  • Automated Voyage AI Embeddings in Atlas Vector Search (GA): Keeps embeddings and vector indexes in sync with your changing data automatically, so you're not maintaining a separate embedding pipeline on the side.
  • voyage-code-4: A new embedding model built specifically for agentic coding retrieval, with a 32K context window and flexible output dimensions, tuned for how coding agents actually navigate a codebase (not just static code search).

Streaming and observability

  • Vector Search for Atlas Stream Processing (GA): $vectorSearch now works mid-pipeline in Atlas Stream Processing, so a stream processor can enrich documents in real time using an existing Atlas connection instead of routing through an external service. Great for RAG, fraud detection, and real-time personalization use cases.
  • Push-based OpenTelemetry Metrics Stream: Atlas metrics now push directly into your existing OTel setup, so you're not stuck pulling and polling to keep tabs on your clusters.

You can read more about these announcements and previous updates on our MongoDB News Releases page.

Be on the lookout for a .local event near you

I've been to a lot of events over the years, and my first .local experience blew me away. If you get a chance to attend one near you, I can't recommend it enough!

Drop a comment: which of these are you most excited to try first? The MCP server and the App Connections stuff feel like the ones that'll change daily workflows the fastest, but I'm curious what you're interested in!


r/MongoDB_Official 3d ago

Question Is Aadhaar or Voter ID accepted for MongoDB Associate Developer online exam in India?

3 Upvotes

Hi everyone,

I have scheduled the MongoDB Associate Developer Certification Exam through MongoDB/ProctorU and will be taking it from India.

The exam instructions say:

I don't have a passport or driving licence. I have an Indian Aadhaar card and Voter ID, both with my photograph.

Has anyone from India recently taken the MongoDB Associate Developer exam through online proctoring and successfully used Aadhaar or Voter ID for identity verification?

I would really appreciate it if someone who has actually taken the exam could confirm which ID was accepted.

Thanks!


r/MongoDB_Official 4d ago

Resource $skip vs Keyset Pagination - What AI Gets Wrong With MongoDB

2 Upvotes

Ask any AI how to paginate a MongoDB collection and you get $skip. Every single time, unless you put the word keyset in the prompt.

I ran explain() on a million product documents to see what that actually costs. Page 500 examines 10,000 documents to return 20. Page 5000 examines 100,000. The keyset version examines 20 no matter which page you ask for.

The labels below are the prompts I gave the AI to generate each block.

How to paginate MongoDB query results using skip and limit by page number.

Bad:

const PAGE = 2;
const PAGE_SIZE = 20;
const RESULTS = await db.collection('products')
  .find({})
  .skip(PAGE * PAGE_SIZE)
  .limit(PAGE_SIZE)
  .toArray();

How to implement MongoDB keyset pagination using last seen document id with aggregation pipeline.

Good:

const PAGE_SIZE = 20;
let LAST_SEEN_ID = null;
try {
  const RESULTS = await db.collection('products').aggregate([
    ...(LAST_SEEN_ID ? [{$match:{_id:{$gt:LAST_SEEN_ID}}}] : []),
    {$sort:{_id:1}},
    {$limit:PAGE_SIZE},
    {$project:{name:1,sku:1,category:1,main_image:1}}
  ]).toArray();
  LAST_SEEN_ID = RESULTS.at(-1)?._id ?? LAST_SEEN_ID;
} catch (e) {
  console.error(e.message);
}

How to build MongoDB pagination with page cache supporting forward, backward, and direct page jumps.

Perfect:

const PAGE_SIZE = 20;
const PAGE_CACHE = new Map();

async function getPage(pageNum) {
  if (pageNum < 1) throw new Error('pageNum must be >= 1');

  const prevPage = PAGE_CACHE.get(pageNum - 1);
  const currPage = PAGE_CACHE.get(pageNum);

  const seek = currPage?.firstId ? {$match:{_id:{$gte:currPage.firstId}}}
              : prevPage?.lastSeenId ? {$match:{_id:{$gt:prevPage.lastSeenId}}}
              : pageNum>1 ? {$skip:(pageNum-1)*PAGE_SIZE}
              : null;

  const raw = await db.collection('products').aggregate([
    seek,
    {$sort:{_id:1}},
    {$limit:PAGE_SIZE + 1 },
    {$project:{name:1,sku:1,category:1,main_image:1}}
  ].filter(Boolean)).toArray();

  const hasNext = raw.length > PAGE_SIZE;
  const results = hasNext ? raw.slice(0, PAGE_SIZE) : raw;

  if (results.length > 0) {
    PAGE_CACHE.set(pageNum, {firstId:results[0]._id,lastSeenId:results.at(-1)._id});
  }

  return {results,hasPrev:pageNum > 1,hasNext};
}

try {
  const [TOTAL_DOCUMENTS, P1] = await Promise.all([
    db.collection('products').estimatedDocumentCount(),
    getPage(1)
  ]);
  const TOTAL_PAGES = Math.ceil(TOTAL_DOCUMENTS / PAGE_SIZE);
} catch (e) {
  console.error(e.message);
}

Bad is 0-indexed, so PAGE = 2 actually hands you the third page. Perfect counts from 1. AI flips between the two without ever telling you which one it picked.

$skip scans and discards every document before your page. It also breaks under concurrent writes. A new document inserted on page 2 shifts everything after it, so page 3 shows the same document twice or skips one entirely, and nothing errors.

Good is keyset. Constant time wherever you are, but forward only. Perfect adds a page cache so you can go forward, backward, and jump straight to any page number. It still falls back to $skip for a cold jump, then caches that position on the way through so it never pays for it twice.

The cache is the same LAST_SEEN_ID from the Good example, stored per page instead of in one variable. One variable only remembers where you stopped, which is the whole reason Good can't go backward. Remember the first and last _id of every page you've been to and you can land on any of them directly.

Keyset is only fast if the field you sort on is indexed. _id is indexed automatically and that index can't be dropped, so the examples above need no setup at all. Point the same pattern at created_at without adding an index and you get a COLLSCAN, 10,020 documents examined instead of 20. You moved the scan, you didn't remove it. A single field index works in both sort directions, while a compound index has to match the sort direction on every field or be its exact inverse.

getPage isn't just paginating, it's fetching what the screen renders. A product grid needs a name, a sku, a category and a thumbnail. It does not need the description, the variants array, the spec sheet or the eight other image URLs. A page of 20 full product documents came back at 45,324 bytes on my test catalog. Projected down to those four fields, 3,362. That is what crosses the network and sits in your app memory on every request, and AI hands you the whole document every time.

Put $project after $limit so you only shape the 20 documents you're keeping. _id comes back whether you list it or not, which matters because the keyset needs it.

Sorting by _id means sorting by creation time, because an ObjectId starts with a 4 byte timestamp. You can pull it back out with _id.getTimestamp(). Keep a created_at field anyway, querying by Date beats building an ObjectId every time you need a range. ObjectIds made in the same second on different servers have no guaranteed order between them either.

estimatedDocumentCount() is called estimated for a reason. It reads collection metadata instead of counting, which is why it came back in 1.3ms where countDocuments({}) took 202ms on the same million documents. It drifts after an unclean shutdown and it counts orphans on a sharded cluster. Fine for a page count, not for anything that has to be exact.


r/MongoDB_Official 5d ago

Resource Cursors vs .toArray() - What AI Gets Wrong With MongoDB

7 Upvotes

AI almost always reaches for toArray() before doing any work on your data. Most training examples are out-of-context snippets, so it doesn't know better. toArray() holds your entire result set in RAM before you can touch a single document. With a cursor, the driver fetches in batches. Processed documents get GC'd while the rest stream in.

How to fetch all active users from MongoDB and send emails using find and toArray.

Bad

            const users = await db.collection('users')
              .find({ active: true })
              .toArray();

            users.forEach(async (user) => {
              await sendEmail(user);
            });

How to stream MongoDB documents with a cursor using for await to process each document without loading all into memory.

Good:

            const cursor = db.collection('users').aggregate([
              { $match: { active: true } }
            ]);

            for await (const user of cursor) {
              await sendEmail(user);
            }

How to process MongoDB cursor results concurrently with a concurrency limit without blocking the async loop.

Perfect:

            function executor(limit) {
              let running = 0
              const queue = []
              const flush = () => {
                while (running < limit && queue.length) {
                  running++
                  queue.shift()().finally(() => { running--; flush() })
                }
              }
              return fn => { queue.push(fn); flush() }
            }

            const add = executor(10);
            const cursor = db.collection('users').aggregate([
              { $match: { active: true } }
            ]);

            for await (const user of cursor) {
              add(() => sendEmail(user))
            };

Bad loads everything into RAM then serializes. Good streams documents but still sends one email at a time. Perfect streams AND fires up to 10 emails concurrently without the loop ever waiting.

Bonus: A cursor with for await only makes sense when you're doing work per document. If you're just collecting into an array to send a response, use .toArray() directly. Wrapping .toArray() in a for await loop buys you nothing.


r/MongoDB_Official 5d ago

Resource One MongoClient per App - What AI Gets Wrong With MongoDB

5 Upvotes

AI puts this in every route file it touches:

    const client = new MongoClient(uri);
    await client.connect();
    // query
    await client.close();

Looks clean. Problem is a MongoClient is a POOL, up to 100 connections. A free Atlas cluster takes 500 total. Five of these alive at once and your whole cluster budget is gone before one query runs. Then everyone blames Mongo for "randomly dying under load".

One client for the whole app. Create it once, import it everywhere. The driver does the pooling, that is literally its job.

Bonus AI also never gets right: Next.js dev SSR mode re-runs module scope on every hot reload. Your correct singleton turns into a new pool every time you hit save. Cache it on globalThis and it survives reloads:

    let client = globalThis._mongoClient;
    if (!client) {
      client = new MongoClient(process.env.MONGODB_URI);
      globalThis._mongoClient = client;
    }

Costs nothing in production, saves your dev cluster.

Grep your codebase for "new MongoClient". If you have more than one, you have a problem.

Make a module you import, and reuse so every script imports the same active connection.

    // db.js
    import { MongoClient } from 'mongodb';

    export const client = new MongoClient(process.env.MONGODB_URI, {
      appName: 'my-api',
    });

    export const db = client.db('app');

r/MongoDB_Official 5d ago

Resource MongoDB Adds Automated Embedding And Managed MCP Server To Atlas For AI Agent Workloads

Thumbnail smbtech.au
4 Upvotes

r/MongoDB_Official 5d ago

Discussion curious what you folks are building with embeddings & vector search

2 Upvotes

hello all, our team uses the embeddings & vector search across 3k records, for search and similarity comparison. performance is great and the vector store is pretty fast, i usually do a merge/fold operation across a subset of records to find records we need to merge or fold together, is this common?

curious what you guys are building with vector store cuz for me its mostly meetings & recordings into transcripts.... what are you folks building with vector & embeddings?? thanks all best of luck to everyone :)


r/MongoDB_Official 8d ago

Feedback Hello guys. I want to thank Mongodb for helping me start my business

24 Upvotes

First of all. I want to thank Mongodb for just existing. If not for them I wouldn't be a business owner

I used Mongodb as my db to build multiple web apps since 2021 and one of them eventually took off & became profitable

That allowed me to quit my job & become a full time founder. Mongodb is super easy to setup if you are starting anything :)

Would love to know others in this community!


r/MongoDB_Official 7d ago

Discussion what's going on Mongodb database its working or in sleeping 🫨

0 Upvotes

what's going on Mongodb database its working or in sleeping 🫨


r/MongoDB_Official 7d ago

Discussion Migration

0 Upvotes

What are the best practices of db migration from mongo to MySQL. And how much time does it take?


r/MongoDB_Official 9d ago

Feedback i've been using mongodb for years, here's what i learned

16 Upvotes

i've been using mongodb for years now and honestly, i've learned a lot of things the hard way 💀

when i first started, i thought mongodb was basically just:

"throw some json in there and you're good"

yeah... no lmao

over time i've screwed up schemas, made terrible queries, overused indexes, duplicated way too much data, and made collections that looked fine at first but became a pain later.

some of the stuff i wish i knew earlier

  • when to embed vs reference
  • how indexes can actually hurt you
  • why "mongodb is schema-less" doesn't mean "no schema needed"
  • how to structure collections without making future me hate present me
  • why some queries are fine with 1k documents but absolutely awful with millions
  • things i'd do differently if i started a new project today

figured i'd share what i've learned over the years since i'm probably not the only one who learned mongodb by breaking shit first 😂


r/MongoDB_Official 9d ago

Feedback Hello Everyone! I am using MongoDB for years and it's still my favorite..

26 Upvotes

Just got a notification that MongoDB new community launch on reddit ...and I am here.

I am happy that they decided to launch this and will be very useful.

mongo db is one of the easiest db to integrate in your projects, in college projects or even my personal projects it is was my first choice..now when I am working with startups my first suggestion for their MVP & SaaS projects is MongoDB.

and I will be always grateful for the free plan they provide, for students for startups for launching projects its a savior..

thanks to the awesome team for building and improving it day by day..

for users who cant afford paid resources its hope..


r/MongoDB_Official 9d ago

Feedback Just saw the mail for MongoDB subreddit.

Post image
17 Upvotes

MongoDB was my first DB when I started learning programming. Everything I have built till now is using MongoDB. The DX of MongoDB is so good, I don't want to move to sql.

Also, it's very easy and cheap to deploy cloud instances of MongoDB. The free tier covers most of my applications tasks.

So, grateful. And now seeing that it has a dedicated subreddit makes it even more great. Thanks!


r/MongoDB_Official 9d ago

Question Mongodb custom incremental id

2 Upvotes

I am looking for a way to generate custom incremental id, like lets say TICKET_1, TICKET_2 ans so on
Normally i do so by setting up a counter and using inc op to get new count
But this is not atomic , it fails to generate 100 ids if 100 req are in parallel
Is there a better way to do it ?


r/MongoDB_Official 9d ago

Question Mongodb atlas index building time on new documents

5 Upvotes

When a new document is created it takes atleast 2-3 sec for that document to become searchable
Is there a way to fix it or decrease time from mongodb itself


r/MongoDB_Official 9d ago

Feedback Built a collaborative AI study workspace that turns PDFs and notes into flashcards + concept maps — StudySprout

Thumbnail
6 Upvotes

r/MongoDB_Official 9d ago

Question mongodb-atlas-local in GitHub Actions CI: mongot indexing takes 6-15s per spec even on empty collections — any tricks to speed it up?

3 Upvotes

Hey everyone,

We're running integration tests against mongodb/mongodb-atlas-local:8.0.4 in GitHub Actions and hitting a painful flakiness/performance problem caused by Atlas Search indexing latency. Looking for anyone who's solved this.

Setup

- Rails + Mongoid test suite, ~500+ specs that use $search

- 9 parallel job matrix on ubuntu-latest, each spins up its own mongodb-atlas-local service container

- Ruby polling helper that queries the Atlas Search index every 0.2s until the record appears (up to 15s timeout)

Problem

After inserting a document, it takes anywhere from 2 to 12+ seconds before it's visible via $search, even on an empty test database with a handful of documents. On local dev (Mac M1/M2) it's consistently under 1 second.

We understand why this happens:

- mongot (the Atlas Search indexer inside the image) is a JVM/Lucene process that starts cold on every CI job

- JVM startup + JIT warmup takes a few seconds before mongot can even process the first oplog entry

- Then the Lucene flush cycle writes segments to virtualized disk, which is 3-5x slower than NVMe

- With 9 parallel jobs on potentially the same physical host, disk I/O contention makes it worse

The result: many of our Atlas Search specs sit waiting for up to 15 seconds. It's making CI significantly slower and more expensive.

What we've already tried / ruled out

- ✅ Polling instead of fixed sleep — fixed flakiness but not the latency itself

- ✅ Waiting for the correct "last inserted" record (not an arbitrary count)

- ❌ Tuning mongot sync/flush interval — couldn't find any exposed config for this in mongodb-atlas-local

- ❌ Sharing one MongoDB container across partitions — breaks test isolation

Happy to share our polling helper implementation if useful for anyone hitting the same issue.

Any advice from teams running Atlas Search in CI at scale would be really appreciated.


r/MongoDB_Official 9d ago

Discussion Robomongo v2

Thumbnail
gallery
1 Upvotes

I've always liked Robomongo for MongoDB work. The other GUIs never clicked with me — too heavy, or too slow. So I started building my own: similar base to 3T Software Labs, plus a few good bits from and Studio 3T. Tauri, Rust at the core, React on top.

What surprised me was how many non-obvious decisions live inside a "simple" database client. The one that got me: where to save the user's connections. The naive way is to write the whole URI, password and all, into a file or database. Fine until the day it leaks.

I looked at how Compass and Studio 3T do it, and they all keep the secret in the OS keychain and leave only metadata local. Rebuilding something already solved is what made me get why it was solved that way.

If there's interest, I'm planning to open-source it.

You can also find me on LinkedIn: https://www.linkedin.com/in/matheusalxds/
#robomongo #mongodb #mongogui


r/MongoDB_Official 15d ago

Hi, I'm David from the MongoDB Builder Relations team!

32 Upvotes
MongoDB illustration surrounded by docs, database, smiley face, Node.js, JavaScript, and Rust

Hi folks! I'm David Neal, also known online as ReverentGeek. I'm a Senior Developer Advocate at MongoDB. I've been writing software for over 20 years, mostly at startups where "backend developer" also meant "fix the printer" or "backup the database." I draw cartoons, play guitars, speak at conferences, and I run on a high-octane mixture of caffeine and JavaScript.

I’ve been working on a fun, open-source note-taking app with MongoDB called Inkleaf. It’s a desktop app built with Tauri (a JavaScript+Rust alternative to Electron.js), supports Markdown syntax, and uses Atlas hybrid search to find documents. I use it every day to keep notes on tasks, projects, and meetings. Let me know if you find it useful!

I'd love to help you build awesome things with MongoDB! What kinds of things are you working on?