-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathMongoRepository.cs
More file actions
69 lines (57 loc) · 2 KB
/
MongoRepository.cs
File metadata and controls
69 lines (57 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System.Linq.Expressions;
using MongoDB.Driver;
namespace Cosmos.DataTransfer.MongoExtension;
public class MongoRepository<TDocument> : IRepository<TDocument>
{
private readonly IMongoCollection<TDocument> collection;
public MongoRepository(IMongoCollection<TDocument> collection)
{
this.collection = collection;
}
public async ValueTask Add(TDocument item)
{
await collection.InsertOneAsync(item);
}
public async ValueTask AddRange(IEnumerable<TDocument> items)
{
await collection.InsertManyAsync(items);
}
public async ValueTask AddRange(params TDocument[] items)
{
await collection.InsertManyAsync(items);
}
public async ValueTask Update(Expression<Func<TDocument, bool>> filter, TDocument value)
{
await collection.FindOneAndReplaceAsync(filter, value);
}
public async ValueTask Remove(Expression<Func<TDocument, bool>> filter)
{
await collection.DeleteOneAsync(filter);
}
public async ValueTask RemoveRange(Expression<Func<TDocument, bool>> filter)
{
await collection.DeleteManyAsync(filter);
}
public IQueryable<TDocument> AsQueryable()
{
return collection.AsQueryable();
}
public async IAsyncEnumerable<TDocument> FindAsync(FilterDefinition<TDocument> filter, int? batchSize = null)
{
var findOptions = new FindOptions<TDocument, TDocument>();
// Only apply batch size if it's provided and positive; invalid values are silently ignored
// to maintain backward compatibility and prevent exceptions during data migration
if (batchSize.HasValue && batchSize.Value > 0)
{
findOptions.BatchSize = batchSize.Value;
}
using var cursor = await collection.FindAsync(filter, findOptions);
while (await cursor.MoveNextAsync())
{
foreach (var document in cursor.Current)
{
yield return document;
}
}
}
}