在查询中限制 MongoDB 查询结果。

huangapple go评论69阅读模式
英文:

limit results of mongodb query in query itself

问题

可以使用mongodb查询中的limit函数来限制结果集。

https://stackoverflow.com/questions/40356608/mongodb-limit-find-results

但我正在创建一个API,可以通过发送原始的BsonDocument来查询mongodb,该API使用C#的MongoClient来查找结果。

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;
}

但是是否有办法在BsonDocument本身中限制结果?也许可以添加一个过滤器?

英文:

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

https://stackoverflow.com/questions/40356608/mongodb-limit-find-results

But I am creating an API with with you can query mongodb by sending a raw BsonDocument and the api uses C# MongoClient to find results.

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

    var col = db.GetCollection&lt;BsonDocument&gt;(collection);

    var filter = BsonDocument.Parse(qry);

    var result = await col.FindAsync(filter);

    string json = &quot;&quot;;

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

    return json;
}

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

答案1

得分: 1

IMongoCollectionExtensions.FindAsync&lt;TDocument&gt; 方法 (IMongoCollection&lt;TDocument&gt;, Expression&lt;Func&lt;TDocument, Boolean&gt;&gt;, FindOptions&lt;TDocument, TDocument&gt;, CancellationToken) 中,您可以使用 FindOptions 中的 Limit 属性 来限制返回的文档数量。

var result = await col.FindAsync(filter, new FindOptions&lt;BsonDocument&gt;
            {
                Limit = 100 // 要返回的文档数量
            });
英文:

From the IMongoCollectionExtensions.FindAsync&lt;TDocument&gt; Method (IMongoCollection&lt;TDocument&gt;, Expression&lt;Func&lt;TDocument, Boolean&gt;&gt;, FindOptions&lt;TDocument, TDocument&gt;, 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&lt;BsonDocument&gt;
            {
                Limit = 100 // Number of document(s) to be returned
            });

huangapple
  • 本文由 发表于 2023年7月10日 19:51:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76653454.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定