zoukankan      html  css  js  c++  java
  • 使用NoRM操作MongoDB

    NoRM是.NET平台下MongoDB的第三方驱动,可以使用强类型的类操作MongoDB。使用NoRM非常简单,只需要在工程中引用Norm.dll即可。下面来看一个例子。

    首先建立一个表示人员信息的模型

    View Code
    class Person
    {
    [MongoIdentifier]
    publicstring ID
    {
    get
    {
    return _id;
    }
    }
    publicstring Name { get; set; }
    publicint Age { get; set; }
    public List<string> Phone { get; set; }

    privatestring _id;

    public Person()
    {
    _id
    = Guid.NewGuid().ToString();
    Phone
    =new List<string>();
    }

    publicvoid AddPhone(string phone)
    {
    Phone.Add(phone);
    }
    }

     接下来连接数据库

    View Code
    using (var db =new Mongo("Person", "127.0.0.1", "27017", null))
    {
    var personColl
    = db.Database.GetCollection<Person>("Person");
    }

     新增数据并显示

    View Code
    Person person1 =new Person();
    person1.Name
    ="Person1";
    person1.Age
    =1;
    person1.AddPhone(
    "13500000001");
    person1.AddPhone(
    "13500000002");

    Person person2
    =new Person();
    person2.Name
    ="Person2";
    person2.Age
    =2;
    person2.AddPhone(
    "13500000003");
    person2.AddPhone(
    "13500000004");

    personColl.Insert(person1);
    personColl.Insert(person2);
    ShowPersonList(personColl);

    显示部分代码如下:

    View Code
    privatestaticvoid ShowPersonList(IMongoCollection<Person> personColl)
    {
    foreach (Person person in personColl.AsQueryable())
    {
    Console.WriteLine(
    "Person Name is {0}, age is {1}", person.Name, person.Age.ToString());
    string phoneInfo ="Phone Numbers:";
    foreach (var phone in person.Phone)
    {
    phoneInfo
    += phone +"";
    }
    Console.WriteLine(phoneInfo);
    }
    Console.WriteLine(
    "Person Numbers:{0}", personColl.Count());
    }

    修改数据

    View Code
    person2.Phone.RemoveAt(0);
    person2.Age
    =3;
    personColl.Save(person2);
    ShowPersonList(personColl);

    删除数据

    View Code
    personColl.Delete<Person>(person1);
    ShowPersonList(personColl);

    结果显示如下:

  • 相关阅读:
    linux超级终端minicom的使用方法
    linux常用命令
    chmod 777 修改权限
    linux mount挂载设备(u盘,光盘,iso等 )使用说明
    logcat的调试 比较有用的几个命令
    git分支
    Debug和Release区别
    【Linux】linux常用基本命令
    Git代码仓库的建立流程
    Linux记录-JMX监控Tomcat上传到falcon
  • 原文地址:https://www.cnblogs.com/saville/p/1988221.html
Copyright © 2011-2022 走看看