zoukankan      html  css  js  c++  java
  • MongoDB 学习笔记四 C#调用MongoDB

    网址:http://blog.csdn.net/xundh/article/details/49449467

    驱动

    C#/.NET Driver VersionMongoDB 2.4MongoDB 2.6MongoDB 3.0
    Version 2.0
    Version 1.10
    Driver Version.NET 3.5.NET 4.0.NET 4.5Mono 2.10Mono 3.x
    Version 2.0      
    Version 1.10

    我这里下载1.10版本,framework 4.0环境。

    使用

    连接

    using MongoDB.Bson;
    using MongoDB.Driver;
    var client = new MongoClient("mongodb://localhost:27017");
    var server = client.GetServer();
    var database = server.GetDatabase("foo");
    var collection = database.GetCollection<BsonDocument>("bar");
    
    await collection.InsertOneAsync(new BsonDocument("Name", "Jack"));
    
    var list = await collection.Find(new BsonDocument("Name", "Jack"))
        .ToListAsync();
    
    foreach(var document in list)
    {
        Console.WriteLine(document["Name"]);
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    Document是实体类

    using MongoDB.Bson;
    using MongoDB.Driver;
    public class Person
    {
        public ObjectId Id { get; set; }
        public string Name { get; set; }
    }
    var client = new MongoClient("mongodb://localhost:27017");
    var server = client.GetServer();
    var database = server.GetDatabase("foo");
    var collection = database.GetCollection<Person>("bar");
    
    await collection.InsertOneAsync(new Person { Name = "Jack" });
    
    var list = await collection.Find(x => x.Name == "Jack")
        .ToListAsync();
    
    foreach(var person in list)
    {
        Console.WriteLine(person.Name);
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    实体类给下面的代码使用

    public class Entity
    {
        public ObjectId Id { get; set; }
        public string Name { get; set; }
    }
    • 1
    • 2
    • 3
    • 4
    • 5

    插入

    var entity = new Entity { Name = "Tom" };
    collection.Insert(entity);
    var id = entity.Id; // Insert will set the Id if necessary (as it was in this example)
    • 1
    • 2
    • 3

    查找

    var query = Query<Entity>.EQ(e => e.Id, id);
    var entity = collection.FindOne(query);
    // var entity = collection.FindOneByIdAs<Entity>(id);
    
    /*
     定义一个查询:查询stdid=1的文档
    FindOneArgs args = new FindOneArgs {
        Query = Query.EQ("stdid", 1),//查询stdid field等于1的document。
    };
    //查询
    var std = collection.FindOneAs<Student>(args);
    */
    /*
     查询多条
     IMongoQuery query = Query.GTE("stdid",2);
     var result=collection.FindAs<Student>(Query.GTE("stdid",2));
     foreach (var each in result) {
         Console.WriteLine(each.stdName);
     }
    */
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    保存

    entity.Name = "Dick";
    collection.Save(entity);
    • 1
    • 2

    更新

    var query = Query<Entity>.EQ(e => e.Id, id);
    var update = Update<Entity>.Set(e => e.Name, "Harry"); // update modifiers
    collection.Update(query, update);
    • 1
    • 2
    • 3

    删除

    var query = Query<Entity>.EQ(e => e.Id, id);
    collection.Remove(query);
    • 1
    • 2

    这是一个完整的示例:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using MongoDB.Bson;
    using MongoDB.Driver;
    using MongoDB.Driver.Builders;
    
    namespace ConsoleApplication1
    {
        public class Entity
        {
            public ObjectId Id { get; set; }
            public string Name { get; set; }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                var connectionString = "mongodb://localhost";
                var client = new MongoClient(connectionString);
                var server = client.GetServer();
                var database = server.GetDatabase("test");
                var collection = database.GetCollection<Entity>("entities");
    
                var entity = new Entity { Name = "Tom" };
                collection.Insert(entity);
                var id = entity.Id;
    
                var query = Query<Entity>.EQ(e => e.Id, id);
                entity = collection.FindOne(query);
    
                entity.Name = "Dick";
                collection.Save(entity);
    
                var update = Update<Entity>.Set(e => e.Name, "Harry");
                collection.Update(query, update);
    
                collection.Remove(query);
            }
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    参考:http://mongodb.github.io/mongo-csharp-driver/1.10/getting_started/

    LinQ查询

    C# driver 1.8版本开始支持Linq查询。

    var linquery = from e in collection.AsQueryable<SY.Model.User>()
                           //where e.age> 22
                           select e;
    linquery=linquery.Where(c=>c.Name=="张三");
    int count=linquery.Count();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    参考:http://mongodb.github.io/mongo-csharp-driver/1.10/linq/

    Document查询方式

    未测试,参考地址记录在这里。

    //Document docName = new Document { { "字段名1", "输入值1" }, { "字段名2", "输入值2" } };
    /// <summary>
    /// 根据姓名获取用户信息
    /// </summary>
    /// <param name="mUserInfo">用户Model类</param>
    /// <returns>用户泛型集合</returns>
    public List<UserInfo> GetUserByName(UserInfo mUserInfo)
    {
        List<UserInfo> lsUser = new List<UserInfo>();
        using (Mongo mongo = new Mongo("mongodb://localhost"))
        {
            MongoDatabase mongoDatabase = mongo.GetDatabase("UserInfo") as MongoDatabase;
            MongoCollection<Document> mongoCollection = mongoDatabase.GetCollection<Document>("myCollection") as MongoCollection<Document>;
            mongo.Connect();
            Document docName = new Document { { "FirstName", "aaa" }, { "LastName", "bbb" } };
            MongoDB.ICursor<Document> users = mongoCollection.Find(docName);
    
            foreach (Document user in users.Documents)
            {
                UserInfo mUser = new UserInfo();
                mUser.FirstName = user["FirstName"].ToString();
                mUser.LastName = user["LastName"].ToString();
                mUser.CorporationName = user["CorporationName"].ToString();
                mUser.Phone = user["Phone"].ToString();
                mUser.Email = user["Email"].ToString();
                mUser.UserType = user["UserType"].ToString();
                lsUser.Add(mUser);
            }
        }
    
        return lsUser;
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    http://weishangxue.blog.163.com/blog/static/21575188201181633811102/ 
    http://mikaelkoskinen.net/post/mongodb-aggregation-framework-examples-in-c

  • 相关阅读:
    apache .htaccess文件详解和配置技巧总结
    看懂UML类图和时序图
    你必须了解的Session的本质
    php中fopen不能创建中文文件名文件的问题
    RabbitMQ消费服务关掉时会删除exchange,导致生成服务发布内容失败
    fastjson 调用JSONObject.toJSON(),如果是解析泛型对象会报OutOfMemoryError错误
    docker启动springboot项目,中文打印乱码
    Spring事务嵌套抛异常org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
    Springboot + SLF4j + Log4j2 打印异常日志时,耗时要5-6秒
    SVN设置全局忽略提交文件或者目录
  • 原文地址:https://www.cnblogs.com/zxtceq/p/7692200.html
Copyright © 2011-2022 走看看