Hybrid search in one aggregation stage, plus a simple way to pick the weights per query.
Ask a vector index for "error E1042 on upload" and it will happily return articles about uploads failing in general. Embeddings are great at meaning, but exact tokens like error codes, SKUs and function names tend to get blurred. Full-text search finds those tokens, but misses a question phrased in different words.
You want both. MongoDB made native hybrid search generally available on June 30, 2026, with two aggregation stages: $rankFusion and $scoreFusion. In this post I focus on $rankFusion: how it scores documents, how to call it from Python, and how to weight it per query instead of with one fixed number.
How $rankFusion scores documents
$rankFusion runs each input pipeline, removes duplicates, and ranks the combined list with Reciprocal Rank Fusion (RRF). Each time a document appears in a pipeline, it gets weight / (60 + rank). The scores are summed across pipelines. The constant 60 is fixed by MongoDB, and ranks start at 1.
The important detail: RRF ignores the raw scores. A BM25 score of 14 and a cosine similarity of 0.82 are on different scales, so RRF only looks at positions. That is why you can mix them without any normalization.
Here is the same formula in plain Python, so you can test ideas without a cluster:
K = 60 # MongoDB's fixed rank constant
def rrf(ranked: dict[str, list[str]],
weights: dict[str, float] | None = None) -> list:
"""Weighted Reciprocal Rank Fusion (ranks start at 1)."""
weights = weights or {}
scores: dict[str, float] = {}
for name, docs in ranked.items():
w = weights.get(name, 1.0)
for rank, doc_id in enumerate(docs, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + w / (K + rank)
return sorted(scores.items(), key=lambda kv: kv[1], reverse=True)
# The worked example from the MongoDB $rankFusion docs
print(rrf({
"search": ["Document3", "Document2", "Document1"],
"vector": ["Document1", "Document2", "Document3"],
}))
I ran this and it printed 0.0322664585 for Document1, the same value the MongoDB docs show for that example. It also shows a nice property: Document1 and Document3 tie exactly, because each one is first in one list and third in the other.
The real query in Python
You need two indexes on the same collection: a normal search index for $search and a vectorSearch index for $vectorSearch. No new index type is needed for hybrid search. Then the query is one stage:
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/?directConnection=true")
kb = client["support"]["articles"]
def hybrid_search(query: str, query_vector: list[float], k: int = 5):
pipeline = [
{"$rankFusion": {
"input": {"pipelines": {
"vector": [{"$vectorSearch": {
"index": "vector_index",
"path": "embedding",
"queryVector": query_vector,
"numCandidates": 200,
"limit": 20,
}}],
"text": [
{"$search": {
"index": "search_index",
"text": {"query": query, "path": "body"},
}},
{"$limit": 20},
],
}},
"combination": {"weights": pick_weights(query)},
"scoreDetails": True,
}},
{"$limit": k},
{"$project": {
"title": 1,
"score": {"$meta": "score"},
"details": {"$meta": "scoreDetails"},
}},
]
return list(kb.aggregate(pipeline))
Two notes. $search cannot limit itself, so add $limit inside its sub-pipeline, as the docs recommend. And scoreDetails shows the rank and weight from each pipeline, which is the fastest way to understand why a result won.
I did not run this query here, because it needs a deployment with Search enabled. The quickest free option is a local Atlas deployment in Docker with atlas local setup (the older atlas deployments commands are deprecated).
Pick the weights per query
MongoDB recommends weighting lexical and vector queries per query instead of using one static weight for everything. A simple rule works well as a starting point: if the query contains something that looks like a code, trust the keyword side more.
import re
CODE_LIKE = re.compile(r"\b[A-Z]{1,4}-?\d{2,}\b|\b\w+\(\)")
def pick_weights(query: str) -> dict[str, float]:
"""Lean on keywords when the query has an exact token."""
if CODE_LIKE.search(query):
return {"vector": 1.0, "text": 2.0}
return {"vector": 1.5, "text": 1.0}
# Illustrative ranked lists, not real search output
ranked = {
"vector": ["kb-retry-guide", "kb-timeouts", "kb-E1042", "kb-auth"],
"text": ["kb-E1042", "kb-error-codes", "kb-retry-guide"],
}
for q in ["why does my upload keep failing", "error E1042 on upload"]:
print(q, rrf(ranked, pick_weights(q))[:3])
With these made-up lists, the run printed kb-retry-guide first (0.04046) for the plain-English question and kb-E1042 first (0.04866) for the error-code question. The margins are small: in the second case kb-retry-guide was right behind at 0.04814. That is a feature. Weights nudge the order; a document that ranks well in both lists still stays near the top.
In a real system I would replace the regex with a check you can measure: build a small set of queries with known good answers, and compare weight settings on it.
Limits to know before you ship
-
$rankFusionneeds MongoDB 8.0 or later.$scoreFusion, which combines normalized scores instead of ranks, needs 8.3 or later. - Sub-pipelines run one after another, not in parallel, so each one adds latency.
- All sub-pipelines must use the same collection. For cross-collection search, use
$unionWith. - Sub-pipelines cannot reshape documents. Put
$projectafter the fusion stage, as above. - There is no pagination, so keep each sub-pipeline's limit small and focused.
Takeaway
Vector search and keyword search fail in different ways, and RRF lets you combine them without fighting over score scales. Start with $rankFusion, look at scoreDetails to see why things rank where they do, and set weights per query. Move to $scoreFusion only when you need the actual scores, not just the order.
Sources
- How to Perform Hybrid Search – MongoDB Docs
- $rankFusion Aggregation Stage – MongoDB Docs
- Now GA: Hybrid Search with $rankFusion and $scoreFusion – MongoDB
- Create a Local Atlas Deployment – Atlas CLI Docs
- Harness the Power of Atlas Search and Vector Search with $rankFusion – MongoDB Blog
Let's Connect
I write about AI agents, RAG, and .NET every week. If this post helped you, let's connect:
Follow me here for the next post!
Top comments (0)