使用c#query mongodb文档字段值

时间:2017-04-17 18:10:53

标签: c# mongodb

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

我有收集的文件,我输出到控制台,代码如下:

{“_ id”:ObjectId(“58f034bf5c57ef10bc4f8d3d”),“firstname”:“Christano”,“birthdate”:ISODate(“1995-04-14T02:32:31Z”),“country”:“Brazil”} {“_ id”:ObjectId(“58f0c7bb5c57ef10bc506216”),“firstname”:“Pele”,“birthdate”:ISODate(“2007-05-14T02:32:31Z”),“country”:“Brazil”} {“_ id”:ObjectId(“58f0ca995c57ef10bc506763”),“firstname”:“Anthony”,“birthdate”:ISODate(“2010-04-14T02:32:31Z”),“country”:“Italy”}

如何将单个字段值写入控制台,以便我可以单独存储和操作这些值?

using MongoDB.Bson;
using MongoDB.Driver;

var playerfirstname;
var playerbirthdate;
var playercountry;

var client = new MongoClient("mongodb://localhost:27017");
var DB = client.GetDatabase("football");
var collection = DB.GetCollection<BsonDocument>("players");

var filter = Builders<BsonDocument>.Filter.Eq("country", "Brazil");
var cursor = collection.Find(filter).ToCursor();
foreach (var document in cursor.ToEnumerable())
{
    Console.WriteLine(document);
}

1 个答案:

答案 0 :(得分:1)

您应该定义类似以下的类

internal class Player
{
    public ObjectId Id { get; set; }
    public string firstname { get; set; }
    public DateTime birthdate { get; set; }
    public string country { get; set; }
}

然后更改集合类型,如下所示:

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

然后只应用LINQ,你可以过滤掉所有国家不是巴西的玩家并访问每个玩家的属性,如下所示:

var playersInBrazil = players.AsQueryable()
                             .Where(player => player.country == "Brazil");
foreach(var playerInBrazil in playersInBrazil)
{
    Console.WriteLine(playerInBrazil.firstname);
}