使用最新的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米文档的性能,同时也会非常频繁地调用此查询。
澄清
主要问题是如何构建此查询以产生上述结果,第二个问题是查询将从服务器中消耗多少性能。
感谢。
答案 0 :(得分: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
}
},
};
}
}
}
答案 1 :(得分:0)
您可以使用$project
版本尝试以下聚合。
聚合阶段 - $sort
- $project
- $reduce
。
数组聚合运算符 - $slice
&amp; $add
算术运算符 - $project
示例:
如果我在第9季到第10季查询排名,那么someId3首先是someId2 之后和someId1是最后一次
以下代码将使用PlayerId
阶段来保留TotalPoints
和TotalPoints
。
`
$slice
将SeasonalPoints
与9
数组一起使用,起始位置为2
并返回$reduce
个元素,后跟$sort
数组值并将每个文档的值相加。
TotalPoints
阶段按$project
值降序排序。
PlayerId
阶段输出class Program {
static void Main(string[] args) {
IMongoClient client = new MongoClient();
IMongoDatabase db = client.GetDatabase("db");
IMongoCollection < PlayerPoints > collection = db.GetCollection < PlayerPoints > ("collection");
var pipeline = collection.Aggregate()
.Project(p => new {
PlayerId = p.PlayerId, TotalPoints = p.SeasonalPoints.Skip(9).Take(2).Aggregate((s1, s2) => s1 + s2)
})
.SortByDescending(s => s.TotalPoints)
.Project(e => new {
e.PlayerId
});
var result = pipeline.ToListAsync();
}
}
值。
db.collection.aggregate([{
"$project": {
"PlayerId": "$_id",
"TotalPoints": {
"$reduce": {
"input": {
"$slice": ["$SeasonalPoints", 9, 2]
},
"initialValue": 0,
"in": {
"$add": ["$$value", "$$this"]
}
}
},
"_id": 0
}
}, {
"$sort": {
"TotalPoints": -1
}
}, {
"$project": {
"PlayerId": "$PlayerId",
"_id": 0
}
}])
Mongo Shell查询:
{{1}}