如何使用C#解析BsonDocument

时间:2018-07-12 11:42:09

标签: c# .net mongodb bson

我刚刚开始学习MongoDb,对nosql(不仅是sql)数据库没有任何经验,所以很遗憾如果答案很明显。我在那里创建了一个包含两个字段的文档。分别是“名称”和“ id”。然后我放入了5个文档。这是我的问题。我不知道如何只列出名称名称而没有任何字段。

 internal static class Program
        {
            // connects to db
            private static readonly MongoClient DbClient = new MongoClient("mongodb://localhost:27017");
            // reads database 
            private static readonly IMongoDatabase Db = DbClient.GetDatabase("STAJDB");
            // list of databases 
            static List<BsonDocument> _collList = Db.ListCollections().ToList();
            // documents 
            private static readonly IMongoCollection<BsonDocument> UserList = Db.GetCollection<BsonDocument>("users");

            public static void Main(string[] args)
            {
                const string documentName = "users";
                CreateUser("ekko", 1023, documentName);
                CreateUser("ryze", 1437, documentName);
                CreateUser("yasuo", 1234, documentName);
                CreateUser("vayne", 873, documentName);
                CreateUser("teemo", 453, documentName);

                ListAllUsers();
            }

            private static void CreateUser(string name, int id, string documentName)
            {
                var personDoc = new BsonDocument();
                var personFirstNameElement = new BsonElement("name", name);  
                personDoc.Add(personFirstNameElement);  
                personDoc.Add(new BsonElement("id", id));  
                UserList.InsertOne(personDoc); 
            }

            private static void ListAllUsers()
            {
                var result = UserList.Find(new BsonDocument()).ToList();
                foreach (var item in result)
                {
                    Console.WriteLine(item);
                }
            }  
          }

输出看起来像这样

{ "_id" : ObjectId("5b4733cfe35d52228c68000b"), "name" : "ekko", "id" : 1023 }
{ "_id" : ObjectId("5b4733cfe35d52228c68000c"), "name" : "ryze", "id" : 1437 }
{ "_id" : ObjectId("5b4733cfe35d52228c68000d"), "name" : "yasuo", "id" : 1234 }
{ "_id" : ObjectId("5b4733cfe35d52228c68000e"), "name" : "vayne", "id" : 873 }
{ "_id" : ObjectId("5b4733cfe35d52228c68000f"), "name" : "teemo", "id" : 453 }

如何仅从中提取名称?谢谢

0 个答案:

没有答案