我有兩個集合,一個用于專案,第二個用于該專案的評級。我想添加兩個值(從專案集合中獲取資料時)平均評分和評分計數。
public class ShopItem { //item structure
public Guid Id {get; set;}
public string Name { get; set;} = string.Empty;
public decimal Price { get; set;}
public string Description { get; set;} = string.Empty;
public SeasonEnum Season {get; set;}
public DateTimeOffset CreatedDate { get; set;}
}
public class RatingModel {
public Guid Id {get; set;}
public Guid UserId {get; set;}
public Guid ShopItemId {get; set;}
[Range(1,5)]
public Int16 Rate {get; set;}
public DateTimeOffset CreatedDate { get; set;}
}
所以我想出要實作這一點,首先我應該查找收視率集合,然后分組以添加平均值和計數,然后使用投影洗掉“查找”欄位。懸停在查找階段后,值變為 bsonDocument,我不知道如何處理它。``
FilterDefinition<ShopItem>? filter = filterBuilder.Empty;
if(filterOptions.NameToMatch!=null){
var nameFilter = filterBuilder.Where(item=>item.Name.Contains(filterOptions.NameToMatch));
filter &= nameFilter;
}
if(filterOptions.SeasonToMatch!=null){
var seasonFilter = filterBuilder.Where(item=>item.Season==filterOptions.SeasonToMatch);
filter &= seasonFilter;
}
var items = await itemsCollection.
Aggregate().
Match(filter).
Lookup("Rate", "Id", "ShopItemId", "Ratings"). // BsonDocument After that line
Group(x => x.Ratings, //
g => new {
AmountOfRatings = g.Count(),
AverageRating = g.Average(x => x.Ratings.Rate) // not exactly sure what syntax there
}
).
Projection(Builders<ShopItem>.Projection.Exclude("Ratings")).
ToListAsync();
uj5u.com熱心網友回復:
在我看來,你不需要$group舞臺。執行$lookup時,Rate集合與ShopItemcollection by連接ShopItemId。因此,從技術上講,評級按分組ShopItemId。
ProjectionDefinition<BsonDocument> projection = new BsonDocument
{
{
"AmountOfRatings",
new BsonDocument("$size", "$Ratings")
},
{
"AverageRating",
new BsonDocument("$avg", "$Ratings.Rate")
}
};
var items = await itemsCollection
.Aggregate()
.Match(filter)
.Lookup("Rate", "_id", "ShopItemId", "Ratings")
.Project(projection)
.ToListAsync();
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/504150.html
