了解MongoDb .NET驱动程序索引

时间:2016-09-19 09:52:49

标签: c# mongodb mongodb-.net-driver

我目前正在研究MongoDb用于大量数据的应用程序。

我在MongoDb中存储的对象如下所示:

public class PowerPlantDataReading
{
    [BsonId]
    public int ID { get; set; }
    [BsonElement("EDIEL")]
    public string EDIEL { get; set; }
    [BsonElement("EndDate")]
    public DateTime EndDate { get; set; }
    [BsonElement("Created")]
    public DateTime Created { get; set; }

    [BsonElement("DataReading")]
    public DataReading DataReading { get; set; }
}

public class DataReading
{
    [BsonElement("Version")]
    public int Version { get; set; }

    [BsonElement("OriginalId")]
    public int OriginalId { get; set; }

    [BsonElement("Unit")]
    public string Unit { get; set; }

    [BsonRepresentation(MongoDB.Bson.BsonType.Double)]
    [BsonElement("Quantity")]
    public decimal Quantity { get; set; }

    [BsonElement("Quality")]
    public string Quality { get; set; }

    [BsonElement("StartDate")]
    public DateTime StartDate { get; set; }        
}

我对MongoDb运行的查询如下所示:

DateTime startDateUtc = DateTime.UtcNow.AddDays(-5);
DateTime endDateUtc = DateTime.UtcNow;

var queryBuilder = Builders<PowerPlantDataReading>.Filter;
var filter = queryBuilder.Where(x => x.EndDate >= startDateUtc && x.EndDate < endDateUtc);

var query = collection.Find(filter).ToListAsync();

return query.Result;

查询返回大约825.000个对象,但运行时间超过4分钟。

然后我尝试创建一个这样的索引:

IMongoCollection<PowerPlantDataReading> collection = GetCollection();
collection.Indexes.CreateOne(Builders<PowerPlantDataReading>.IndexKeys.Descending(x => x.EndDate));

然后再次运行查询,但令我惊讶的是,它根本没有任何区别。

我不确定我是否正确创建索引?如果没有,我应该如何创建索引以获得最佳的查询性能?

提前致谢。

0 个答案:

没有答案