Search code examples
c#mongodbmongodb-querymongodb-.net-driver

Limit the results of MongoDB query in query itself


It's possible to limit the results of a MongoDB query with the limit function:

MongoDB limit find results

But I am creating an API that you can query by sending a raw BsonDocument and the API uses MongoClient to find results.

public async Task<string> Query(string database, string collection, string qry)
{
    var db = Connection.Client.GetDatabase(database);

    var col = db.GetCollection<BsonDocument>(collection);

    var filter = BsonDocument.Parse(qry);

    var result = await col.FindAsync(filter);

    string json = "";

    await result.ForEachAsync(b => json += toJson(b));

    return json;
}

But is there a way to limit results in the BsonDocument itself? Add a filter maybe?


Solution

  • From the IMongoCollectionExtensions.FindAsync<TDocument> Method (IMongoCollection<TDocument>, Expression<Func<TDocument, Boolean>>, FindOptions<TDocument, TDocument>, CancellationToken) method, you can provide the FindOption with Limit property to limit the number of returned document(s).

    var result = await col.FindAsync(filter, new FindOptions<BsonDocument>
                {
                    Limit = 100 // Number of document(s) to be returned
                });