Skip to content

Troubleshooting

Aryeh Citron edited this page Apr 26, 2026 · 1 revision

Troubleshooting

Common Issues

"Item must have an 'id' property" / NullReferenceException on insert

Cause: Your document class doesn't have a property that maps to MongoDB's _id field.

Fix: Add an Id property with [BsonId]:

public class MyDocument
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string? Id { get; set; }
    
    public string Name { get; set; }
}

Empty query results when documents exist

Possible causes:

  1. Serialization mismatch — Your property names don't match the BSON field names. Use [BsonElement("fieldName")] to map them.

  2. Wrong collection name — Check that you're querying the same collection you inserted into.

  3. Filter doesn't match — Test with FilterDefinition<T>.Empty to verify documents exist, then narrow your filter.

"Collection 'xxx' not found" / NullReferenceException on GetCollection

Cause: The collection hasn't been registered or created yet.

Fix: Either insert a document (auto-creates the collection) or register it explicitly:

options.AddCollection<MyDoc>("myCollection");

Aggregation pipeline returns unexpected results

Possible causes:

  1. BsonInt64 vs BsonInt32 — The driver renders $limit and $skip as BsonInt64. Use .ToInt32() when comparing.

  2. $sum produces BsonDouble — The $sum accumulator produces BsonDouble by default. Use .ToInt32() not .AsInt32.

  3. Missing $unwind — If grouping on array fields, you may need $unwind first.

Change stream events not firing

Possible causes:

  1. Not calling MoveNextAsync() — Change stream cursors are pull-based.

  2. Events fired before watch started — Start watching before performing operations.

LINQ query throws NotSupportedException

Cause: The LINQ expression translates to an operator not supported by the emulator.

Fix: Use the builder API (Builders<T>.Filter / .Update) instead of LINQ for complex queries. Check Filter & Update Operators for supported operators.

TTL items still visible in queries

Explanation: TTL eviction is lazy — documents are only removed when a query executes. This matches the behavior of real MongoDB where the TTL background thread runs every 60 seconds.

Fix: Query the collection to trigger eviction, or check that the TTL field contains a valid DateTime / BsonDateTime value.

Unique index not enforced

Check:

  1. The index was created with new CreateIndexOptions { Unique = true }
  2. The index was created before inserting duplicate documents
  3. For sparse indexes, documents missing the indexed field are intentionally allowed

MapReduce throws NotSupportedException

Explanation: MapReduce is deprecated in MongoDB 5.0+. Use the aggregation pipeline instead:

// Instead of MapReduce:
var results = await collection.Aggregate()
    .Group(x => x.Category, g => new { Category = g.Key, Count = g.Count() })
    .ToListAsync();

See Also

Clone this wiki locally