• MongDB简介


    DOC

    参考链接

    BSON类库
    BSON是类似JSON的一种二进制形式的存储格式,简称Binary JSON,它和JSON一样,支持内嵌的文档对象和数组对象,但是BSON有JSON没有的一些数据类型,如Date和BinData类型。它也是MongoDB文档数据库内部的数据存储方式。

    public enum BsonType {
        Double = 0x01,
        String = 0x02,
        Document = 0x03,
        Array = 0x04,
        Binary = 0x05,
        Undefined = 0x06,
        ObjectId = 0x07,
        Boolean = 0x08,
        DateTime = 0x09,
        Null = 0x0a,
        RegularExpression = 0x0b,
        JavaScript = 0x0d,
        Symbol = 0x0e,
        JavaScriptWithScope = 0x0f,
        Int32 = 0x10,
        Timestamp = 0x11,
        Int64 = 0x12,
        MinKey = 0xff,
        MaxKey = 0x7f
    }
    

     

     

    BsonValue和子类

    BsonValue是一种代表BsonType的虚拟类。它是BsonType枚举类的凝聚子类。

    ·可以使用public构造函数生成BsonValue子类

    ·使用静态create函数生成

    ·Use a static property of a subclass of BsonValue(静态的子类属性?)

    ·隐式转换成BsonValue

    BsonType的类型

    可以用下面的例子代码确认BsonValue的属性

    BsonValue value;
    if (value.BsonType == BsonType.Int32) {
        // we know value is an instance of BsonInt32
    }
    if (value is BsonInt32) {
        // another way to tell that value is a BsonInt32
    }
    if (value.IsInt32) {
        // the easiest way to tell that value is a BsonInt32
    }
    

      

    BsonElement

    (Bson元素)
    Bson元素是一个name/value的键值对。
    document.Add(new BsonElement("age", 21)); // OK, but next line is shorter
    document.Add("age", 21); // creates BsonElement automatically
    



    BsonDocument

     
    BsonDocument是name/value键值对的集合。
    BsonDocument构造函数
    • BsonDocument()
    • BsonDocument(string name, BsonValue value)


    参考

    Thread safety(多线程问题)

    只有少部分的C# Driver类是多线程安全的。比如MongoClient,MongoServer,MongoDatabase, MongoCollection 以及MongoGridFS。一般常用的类存在多线程问题,包括MongoCursor以及Bson类库中的所有类(除了其中的BsonSymbolTable是线程安全的)。

    所有的类的静态属性值和函数方法都不会引起多线程问题。

    MongoClient类

    这个类提供使用MongoDB server的基本对象。与MongoDB server服务进行链接的时候,client自动进行连接。(使用了连接池来进行更有效的连接)

    在连接一个副本集的时候,有且只用一个MongoClient实例。

    When you are connecting to a replica set you will still use only one instance of MongoClient, which represents the replica set as a whole. The driver automatically finds all the members of the replica set and identifies the current primary.

    这个类的实例不会引起多线程问题。

    除非其他设置,在默认设置情况下,所有操作需要一个WriteConcern,一个写入确定语句。另外,默认情况下,所有的写操作会锁定,直到server知道要进行写操作。

    MongoServer class

    使用MongoServer类可以进行更多的控制操作。它使用了先进的技术通过一个单个的socket获取数据库以及进行一系列的数据库操作,并且保持数据库的一致性。

    MongoDatabase class
    这是一个描述MongoDB Server的类。通常情况下,一个database只有一个这个类的实例,除非你使用了不同的设置连接了相同的database。因为在这个情况下面,针对每个设置,都有一个实例。

    MongoCursor<TDocument>类

    Find函数不会直接返回确切的查询结果。而是它返回一个游标来枚举检索查询结果。这个query查询语句实际上在你尝试检索第一个结果的时候才会送至服务器。这意味着,你可以通过控制游标检索结果来得到你感兴趣的内容。

    MongoCursor类的实例会造成多线程问题。至少在它被冻结之前不要使用。一旦它是冻结状态下,它就不会造成多线程安全问题。因为它是只读状态。

    WriteConcern class

    WriteConcern 有很多等级,这个类就是用来描述这个等级的。WriteConcern 应用只用来操作那些没有返回的操作。比如Insert 、Save、Update和Remove。

    这个主要就是当Insert、Save、Update和Remove指令发送给服务器之后,会有一个GetLassError命令来确认这些操作是否成功执行了。

     

    client:The MongoClient instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads

      var client = new MongoClient("mongodb://localhost:27017,localhost:27018,localhost:27019");

    database:To get a database, specify the name of the database to the GetDatabase method on client. It’s ok if the database doesn’t yet exist. It will be created upon first use.

       var database = client.GetDatabase("foo");

      var collection = database.GetCollection<BsonDocument>("bar");//The collection variable now holds a reference to the “bar” collection in the “foo” database.

      

    document:Once you have the collection instance, you can insert documents into the collection

    var document = new BsonDocument
    {
        { "name", "MongoDB" },
        { "type", "Database" },
        { "count", 1 },
        { "info", new BsonDocument
            {
                { "x", 203 },
                { "y", 102 }
            }}
    };
    

      collection.InsertOne(document);

      await collection.InsertOneAsync(document);

      var documents = Enumerable.Range(0, 100).Select(i => new BsonDocument("counter", i));

      collection.InsertMany(documents);

      await collection.InsertManyAsync(documents);

    query

      Use the Find method to query the collection. The Find method returns an IFindFluent<TDocument, TProjection> instance that provides a fluent interface for chaining find operation options.

        var document = collection.Find(new BsonDocument()).FirstOrDefault();
    Console.WriteLine(document.ToString());

        var documents = collection.Find(new BsonDocument()).ToList();

      create a filter to pass to the Find method to get a subset of the documents in our collection

        var filter = Builders<BsonDocument>.Filter.Eq("i", 71);

        var document = collection.Find(filter).First();

    fields:Many times we don’t need all the data contained in a document. The Projection builder will help build the projection parameter for the find operation.

      var projection = Builders<BsonDocument>.Projection.Exclude("_id");

      var document = collection.Find(new BsonDocument()).Project(projection).First();

      

    update:There are numerous update operators supported by MongoDB.

      The update methods return an UpdateResult which provides information about the operation including the number of documents modified by the update.

      var update = Builders<BsonDocument>.Update.Set("i", 110);

      var filter = Builders<BsonDocument>.Filter.Eq("i", 10);

      collection.UpdateOne(filter, update);

      

        

    delete:To delete at most 1 document (may be 0 if none match the filter) use the DeleteOne or DeleteOneAsync methods:

    bulk:two types of bulk operations:

    1. Ordered bulk operations.

        Executes all the operations in order and errors out on the first error.

    1. Unordered bulk operations.

        Executes all the operations and reports any errors. Unordered bulk operations do not guarantee the order of execution.

    var models = new WriteModel<BsonDocument>[] 
    {
        new InsertOneModel<BsonDocument>(new BsonDocument("_id", 4)),
        new InsertOneModel<BsonDocument>(new BsonDocument("_id", 5)),
        new InsertOneModel<BsonDocument>(new BsonDocument("_id", 6)),
        new UpdateOneModel<BsonDocument>(
            new BsonDocument("_id", 1), 
            new BsonDocument("$set", new BsonDocument("x", 2))),
        new DeleteOneModel<BsonDocument>(new BsonDocument("_id", 3)),
        new ReplaceOneModel<BsonDocument>(
            new BsonDocument("_id", 3), 
            new BsonDocument("_id", 3).Add("x", 4))
    };
    
    
    // 1. Ordered bulk operation - order of operation is guaranteed
    collection.BulkWrite(models);
    
    // 2. Unordered bulk operation - no guarantee of order of operation
    collection.BulkWrite(models, new BulkWriteOptions { IsOrdered = false });
    

     

    编码教程





  • 相关阅读:
    创建新进程,就三个函数CreateProcessAsUser CreateProcessWithLogonW CreateProcessWithTokenW(附网友的流程)
    一个简单的以User权限启动外部应用程序(用NetUserAdd函数和USER_INFO_1结构体动态添加用户,然后用CreateProcessWithLogonW启动程序)good
    将EXE作为资源,然后在释放到磁盘上并运行该exe程序(使用了FindResource,LoadResource,然后用CFile写成一个文件)
    CreateProcess启动隐藏的外部程序(其实就是CreateDesktop,然后指定STARTUPINFO.lpDesktop)
    封装业务函数
    SQLSERVER 数据库性能的的基本 MVC + EF + Bootstrap 2 权限管理
    Nutch搜索引擎Solr简介及安装
    C#程序的157个建议
    利用XCode来进行IOS的程序开发
    C#操作JSON
  • 原文地址:https://www.cnblogs.com/panpanwelcome/p/7691074.html
Copyright © 2020-2023  润新知