C#MongoDB基于点数组的排名

问题描述 投票:2回答:2

使用最新的C#mongodb驱动程序和.NET 4.5.1。

我想在玩家之间进行一些定制的比赛。假设我有以下型号。

public sealed class PlayerPoints
{
    [BsonId]
    public ObjectId PlayerId;

    public DateTime CreateDate;

    public int Points;
    public int[] SeasonalPoints;

}

我希望能够获得特定SeasonalPoints指数之间的玩家等级。

一个例子:

 {PlayerId : someId1, CreateDate : <someCreateDate>, Points : 1000, SeasonalPoints : [100,100,100,100,100,100,100,100,100,100,100]}
 {PlayerId : someId2, CreateDate : <someCreateDate>, Points : 1000, SeasonalPoints : [100,100,100,100,100,100,100,100,50,150,100]}
 {PlayerId : someId3, CreateDate : <someCreateDate>, Points : 1100, SeasonalPoints : [200,100,100,100,100,100,100,100,0,0,300]}

请注意,这里有10个季节。我正在搜索查询,该查询根据他们的排名返回玩家的排序列表。等级由提供的索引之间的点的总和来设置。

如果我在第9季到第10季查询排名,那么someId3是第一个,someId2之后,someId1是最后一个。如果我在第7-9季查询排名,那么someId1是第一个,someId2是第二个,someId3是第三个。

我考虑过使用聚合,它将如何影响大约1米文档的性能,同时也会非常频繁地调用此查询。

澄清

主要问题是如何构建此查询将产生上述结果,次要问题是查询将从服务器消耗多少性能。

谢谢。

c# mongodb mongodb-.net-driver
2个回答
4
投票

至少,如果托管服务器的机器与数据库的机器不同,您将获得改进的服务器性能。

另一方面,这可能意味着数据库机器可能不太“可用”,因为它太忙于计算聚合结果。这是应该进行基准测试的,因为它因应用程序和应用程序而不时变化。

这取决于用户负载,数据量,主机等。

至于查询,这是一个我验证实际工作的程序:

using System;
using System.Collections.Generic;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;

namespace MongoAggregation
{

public sealed class PlayerPoints
{
    public ObjectId Id { get; set; }

    //Note that mongo addresses everything as UTC 0, so if you store local time zone values, make sure to use this attribute
    [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
    public DateTime CreateDate { get; set; }

    public int Points { get; set; }
    //note that your model did not allow a player to not participate in some season, so I took the liberty of introducing a new sub document.
    //It is better to create sub documents that store metadata to make the query easier to implement
    public int[] SeasonalPoints { get; set; }
}

class Program
{

    static void Main(string[] args)
    {
        //used v 2.4.3 of C# driver and v 3.4.1 of the db engine for this example
        var client = new MongoClient();
        IMongoDatabase db = client.GetDatabase("agg_example");

        var collectionName = "points";
        db.DropCollection(collectionName);

        IMongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>(collectionName);
        IEnumerable<BsonDocument> data = GetDummyData().Select(d=>d.ToBsonDocument());

        collection.InsertMany(data);

        //some seasons to filter by - note transformation to zero based
        var seasons = new[] {6, 7};

        //This is the query body:
        var seasonIndex = seasons.Select(i => i - 1);

        //This shall remove all un-necessary seasons from aggregation pipeline
        var bsonFilter = new BsonDocument { new BsonElement("Season", new BsonDocument("$in", new BsonArray(seasonIndex))) };

        var groupBy = new BsonDocument// think of this as a grouping with an anonyous object declaration
        {
             new BsonElement("_id", "$_id"),//This denotes the key by which to group - in this case the player's id
             new BsonElement("playerSum", new BsonDocument("$sum", "$SeasonalPoints")),//We aggregate the player's points after unwinding the array
             new BsonElement("player", new BsonDocument("$first", "$$CURRENT")),// preserve player reference for projection stage
        };

        var sort = Builders<BsonDocument>.Sort.Descending(doc => doc["playerSum"]);

        var unwindOptions = new AggregateUnwindOptions<BsonDocument>
        {
            IncludeArrayIndex = new StringFieldDefinition<BsonDocument>("Season")
        };

        var projection = Builders<BsonDocument>.Projection.Expression((doc => doc["player"]));

        List<BsonValue> sorted = collection
            .Aggregate()
            .Unwind(x=>x["SeasonalPoints"], unwindOptions)
            .Match(bsonFilter)
            .Group(groupBy)
            .Sort(sort)
            .Project(projection)
            .ToList();

    }

    private static IEnumerable<PlayerPoints> GetDummyData()
    {
        return new[]
        {
            new PlayerPoints
            {
                CreateDate = DateTime.Today,
                SeasonalPoints = Enumerable.Repeat(100,7).ToArray()
            },
            new PlayerPoints
            {
                CreateDate = DateTime.Today,
                SeasonalPoints = new []
                {
                    100,100,100,100,100,150,100
                }
            },
            new PlayerPoints
            {
                CreateDate = DateTime.Today,
                SeasonalPoints = new []
                {
                    100,100,100,100,100,0,300
                }
            },
        };
    }
}
}

0
投票

您可以使用3.4版本尝试以下聚合。

聚合阶段 - qazxsw poi - qazxsw poi - qazxsw poi。

数组聚合运算符 - $project$sort

算术运算符 - $project

示例:

如果我在第9季到第10季查询排名,那么someId3排在第一位,someId2排在第一位,而someId1排在第位

下面的代码将使用$reduce阶段来保持$slice$add。 `

$project使用PlayerIdTotalPoints数组,其起始位置为TotalPoints并返回$slice元素,然后是SeasonalPoints,它取数组值并将每个文档的值相加。

9阶段对2值进行降序排序。

$reduce阶段输出$sort值。

TotalPoints

Mongo Shell查询:

$project
© www.soinside.com 2019 - 2024. All rights reserved.