c#mongodb集合计数并从asqueryable中查找文档结果

时间:2017-04-24 01:58:38

标签: c# mongodb mongodb-query

在我的C#控制台应用程序项目中,我使用MongoDB.Driver.2.4.3连接到MongoDB 3.2.10。

如何计算文档数量,从过滤后的查询中查找第一个和最后一个文档?

    static void Main(string[] args)
    {
        DateTime myTimeConvert = DateTime.Now;

        var client = new MongoClient("mongodb://localhost:27017");
        var DB = client.GetDatabase("football");

        var players = DB.GetCollection<Player>("players");


        var playersInBrazil = players.AsQueryable()
                         .Where(p => p.country == "Brazil");
        //count the number of documents and find the first and the last document from the filtered query 

    }

    internal class Player
    {
        public ObjectId Id { get; set; }
        public string firstname { get; set; }
        public BsonDateTime birthdate { get; set; }
        public string country { get; set; }
        public double goals { get; set; }
    }


}

1 个答案:

答案 0 :(得分:0)

var countPlayersInBrazil = players.AsQueryable().Count(p => p.country == "Brazil");
var firstPlayersInBrazil = players.AsQueryable().First(p => p.country == "Brazil");
var lastPlayersInBrazil = players.AsQueryable().Last(p => p.country == "Brazil");