在c#中更新mongoDB中的特定字段?

时间:2016-03-30 18:57:54

标签: c# mongodb

我是MongoDB的新用户,我使用c#和最新的驱动程序....只想更新名称这样的特定字段?我该怎么做(基于控制台的应用程序)?我已经尝试了很多次但失败了,有更新方法,但无法弄清楚如何使用它们......任何人都可以帮助我吗?

这是我的代码:

 class Student
    {
        public int age { get;  set; }
        public string name { get;  set; }
        public ObjectId id { get;  set; }
        public string fname { get;  set; }

        public Student() { }

        public Student(string name, string fname, int age)
        {

            this.name = name;
            this.fname = fname;
            this.age = age;
        }

    }
 static void Main(string[] args)
        {
            var client = new MongoClient();
            var db = client.GetDatabase("StudentDB");
            var collection = db.GetCollection<Student>("Student");

            Console.WriteLine("Press 1 for Insert \nPress 2 for Search \nPress 3 for Update \nPress 4 for Delete ");

            int _case = Convert.ToInt32(Console.ReadLine());
            switch (_case)
            {
                case 1:
                    Console.WriteLine("Enter Name");
                    string name = Console.ReadLine();
                    Console.WriteLine("Enter Father Name");
                    string father_name = Console.ReadLine();
                    Console.WriteLine("Enter Age");
                    int age = Convert.ToInt32(Console.ReadLine());
                    Student s = new Student(name, father_name, age);
                    collection.InsertOne(s);
                    break;

                case 2:
                    //Search by Age
                    Console.WriteLine("Enter Age");
                    int _age = Convert.ToInt32(Console.ReadLine());
                    var query = from person in collection.AsQueryable<Student>()
                                where person.age > _age
                                select person;
                    foreach (Student q in query)
                    {
                        Console.WriteLine(q.name + " " + q.fname + " " + q.age);
                    }
                    break;

                case 3:





                case 4:
                    //Delete
                    int in_age = Convert.ToInt32(Console.ReadLine());
                    collection.DeleteOne(z => z.age == in_age);
                    Console.WriteLine("Deleted");
                    break;

                default:
                    Console.WriteLine("You have selected wrong option");
                    break;
            }
        }

0 个答案:

没有答案