亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

MongoDB C# 聚合計數

MongoDB C# 聚合計數

C#
慕的地8271018 2022-06-19 10:24:16
我希望使用 C# 驅動程序(V 2.7.0)來聚合一個集合,然后計算結果。假設我有一個 IMongoCollection col,我會這樣聚合:IAsyncCursor<BsonDocument> cursor = col.Aggregate()    .Match(someFilterDefinition)    .Project(someProjectionDefinition)    .Unwind("someFieldName")    .ToCursor();while (cursor.MoveNext()){    foreach (BsonDocument doc in cursor.Current)    {        doStuff(doc);    }}我希望獲得聚合返回的文檔數量。在外殼中你會做這樣的事情db.getCollection("someCollectionName").aggregate(    [        {             "$match" : {                // some match filter            }        },         {             "$project" : {                "someField" : 1            }        },         {             "$unwind" : "$someField"        },         {             "$count" : "count"        }    ],     {         "allowDiskUse" : false    });你會得到一個帶有單個“count”字段的文檔(或沒有文檔),它的前一個階段的元素數量的 int64 值。有一個IAggregateFluent.Count()函數。但是它返回一個 IAggregateFluent 我想要一個 AggregateCountResult 或者只是一個簡單的無符號長。如何使用 Aggregate.Count() 函數?
查看完整描述

1 回答

?
慕哥9229398

TA貢獻1877條經驗 獲得超6個贊

您必須使用 .ToCursor 或 .FirstOrDefault 或類似名稱來完成聚合,而不是僅僅附加 Count() 來獲得聚合階段。FirstOrDefault 返回具有 Count 屬性的 AggregateCountResult。

ulong count = col.Aggregate()
    .Match(someFilterDefinition)
    .Project(someProjectionDefinition)
    .Unwind("someFieldName")
    .Count()
    .FirstOrDefault() // returns AggregateCountResult
    .Count();         // returns ulong


查看完整回答
反對 回復 2022-06-19
  • 1 回答
  • 0 關注
  • 164 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號