簡體   English   中英

使用C#驅動程序在mongodb中查找計算值最高的文檔

[英]Find document with highest calculated value in mongodb using c# driver

有沒有辦法找到在mongo db中具有最高計算值的文檔?

我有一個由int 1-5組成的array屬性。 我想找到平均值最高的文檔。

使用常規的Linq這樣的東西:

var entityWithCalculatedMax = collection.OrderByDescending(x => x.Grade.Sum() / x.Grade.Count()).First();    

有什么建議么?

(我正試圖直接在數據庫中執行此操作,因為我不想檢索所有文檔來獲取該文檔)

不幸的是,這不能使用LINQ語法來完成。 正式的“ Aggregation Pipeline”文檔中記錄了經典的聚合語法,使用起來更容易(更具體)。

輸入示例:

{ _id: 1, Grades: [ 1, 1 ] }
{ _id: 2, Grades: [ 2, 3, 4 ] }
{ _id: 3, Grades: [ 5 ] }

這個想法是在聚合管道中包含四個步驟:

  1. 展開每個Grades數組:對於每個文檔,這將創建n個文檔,其中n是成績數,每個文檔具有一個成績:

    結果:

     { _id: 1, Grades: 1 } { _id: 1, Grades: 1 } { _id: 2, Grades: 2 } { _id: 2, Grades: 3 } { _id: 2, Grades: 4 } { _id: 3, Grades: 5 } 
  2. 通過ID對文檔進行分組 ,在a)平均屬性(您的計算結果)和b)新的Grades屬性中匯總成績,以恢復數組:

    結果:

     { _id: 1, Average: 1.0, Grades: [ 1, 1 ] } { _id: 2, Average: 3.0, Grades: [ 2, 3, 4 ] } { _id: 3, Average: 5.0, Grades: [ 5 ] } 
  3. 平均對文檔進行排序

    結果:與上面相同,因為已經以某種方式訂購了它。

  4. 僅限 1個文檔,因為您只需要第一個結果。

我們可以將其轉換為JSON並針對我們的數據庫執行:

db.gradeDocs.aggregate(
    [
        { $unwind: "$Grades" },
        { 
            $group: {
                _id: "$_id",
                Average: { $avg: "$Grades" },
                Grades: { $push: "$Grades" }
            }
        },
        { $sort: { "Average": 1 } },
        { $limit: 1 }
    ]
)

好的,現在我們如何使用C#驅動程序執行此操作? 語法稍微有些冗長,但本質上是一樣的:

var aggregateArgs = new AggregateArgs();
aggregateArgs.Pipeline =
    new[]
    {
        new BsonDocument("$unwind", "$Grades"), 
        new BsonDocument("$group", 
            new BsonDocument
            {
                {"_id", "$_id"},
                {"Average", new BsonDocument("$avg", "$Grades")},
                {"Grades", new BsonDocument("$push", "$Grades")},
            }),
        new BsonDocument("$sort", new BsonDocument("Average", 1)), 
        new BsonDocument("$limit", 1), 
    };

var resultId = collection
    .Aggregate(aggregateArgs)
    .Single()["_id"]
    .AsObjectId;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM