加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#、Java驱动连接MongoDB以及封装(C#的MongoDBHelper,Java的Mong

发布时间:2020-12-13 12:39:21 所属栏目:百科 来源:网络整理
导读:一.C#驱动连接MongoDB 1.创建项目 执行命令:dotnet new console -n MongoDbDriverDemo ? ? ?2.添加依赖包 执行命令:dotnet? add package MongoDB.Driver --version 2.10.2 ? ? ?3.测试 using System; System.Linq; MongoDB.Bson; MongoDB.Driver; namespac

一.C#驱动连接MongoDB

1.创建项目

执行命令:dotnet new console -n MongoDbDriverDemo

?

?

?2.添加依赖包

执行命令:dotnet? add package MongoDB.Driver --version 2.10.2

?

?

?3.测试

using System;
 System.Linq;
 MongoDB.Bson;
 MongoDB.Driver;

namespace MongoDBDriverDemo
{
    class Program
    {

        async static System.Threading.Tasks.Task Main(string[] args)
        {
            try
            {
                MongoClient client = new MongoClient("mongodb://localhost:27017");

                var database = client.GetDatabase(foovar collection = database.GetCollection<BsonDocument>(bar);

                Console.WriteLine(-----------------添加文档--------------------);
                {
                    var document = new BsonDocument
                               {
                                   { name",MongoDB },{ typeDatabasecount1info BsonDocument
                                       {
                                           { x203y102 }
                                       }}
                               };

                    await collection.InsertOneAsync(document);//异步
                    collection.InsertOne(document);

                    var documents = Enumerable.Range(0,1)">100).Select(i => new BsonDocument(i,i));
                    collection.InsertMany(documents);
                    await collection.InsertManyAsync(documents);
                }
                Console.WriteLine(------------------统计文档--------------------);
                {
                                 
                    var count = collection.CountDocuments( BsonDocument());
                    var asyncCount = await collection.CountDocumentsAsync( BsonDocument());
                    Console.WriteLine(count);
                    Console.WriteLine(asyncCount);
                }
                Console.WriteLine(-----------------查询文档--------------------);
                {
                    Console.WriteLine(------------------查询一个--------------------);
                    { 
                        var document = collection.Find( BsonDocument()).FirstOrDefault();
                        Console.WriteLine(document.ToString());

                        var asyncDocument = await collection.Find( BsonDocument()).FirstOrDefaultAsync();
                        Console.WriteLine(asyncDocument.ToString());
                    }
                    Console.WriteLine(------------------查询多个--------------------);
                    {
                        var documentList = collection.Find( BsonDocument()).ToList();
                        documentList.ForEach(d => Console.WriteLine(d.ToString()));

                        var asyncDocumentList = BsonDocument()).ToListAsync();
                        new BsonDocument()).ForEachAsync(d => Console.WriteLine(d));
                    }
                    {
                        var cursor = collection.Find( BsonDocument()).ToCursor();
                        foreach (var document in cursor.ToEnumerable())
                        {
                            Console.WriteLine(document);
                        }
                    }
                }
                {
                    {
                        var filter = Builders<BsonDocument>.Filter.Eq(71);
                        {
                            var document = collection.Find(filter).First();
                            Console.WriteLine(document);
                        }
                        {
                             collection.Find(filter).FirstAsync();
                            Console.WriteLine(document);
                        }
                    }
                    Console.WriteLine(------------------过滤文档--------------------var filter = Builders<BsonDocument>.Filter.Gt(50var cursor = collection.Find(filter).ToCursor();
                             cursor.ToEnumerable())
                            {
                                Console.WriteLine(document);
                            }
                        }
                        {
                            await collection.Find(filter).ForEachAsync(document => Console.WriteLine(document));
                        }
                    }
                    {
                        var filterBuilder = Builders<BsonDocument>.Filter;
                        var filter = filterBuilder.Gt(50) & filterBuilder.Lte(100 Console.WriteLine(document));
                        }
                    }
                }
                Console.WriteLine(------------------排序文档--------------------var filter = Builders<BsonDocument>.Filter.Exists();
                    var sort = Builders<BsonDocument>.Sort.Descending( collection.Find(filter).Sort(sort).First();
                    }

                    {
                         collection.Find(filter).Sort(sort).FirstAsync();
                    }
                }
                Console.WriteLine(var projection = Builders<BsonDocument>.Projection.Exclude(_id BsonDocument()).Project(projection).First();
                        Console.WriteLine(document.ToString());
                    }
                    {
                         BsonDocument()).Project(projection).FirstAsync();
                        Console.WriteLine(document);
                    }
                }
                Console.WriteLine(------------------更新文档--------------------------------------更新一个--------------------10);
                        var update = Builders<BsonDocument>.Update.Set();
                        {
                            collection.UpdateOne(filter,update);
                        }
                        {
                             collection.UpdateOneAsync(filter,update);
                        }
                    }
                    Console.WriteLine(------------------更新多个--------------------var filter = Builders<BsonDocument>.Filter.Lt(var update = Builders<BsonDocument>.Update.Inc(var result = collection.UpdateMany(filter,update);
                            if (result.IsModifiedCountAvailable) Console.WriteLine(result.ModifiedCount);
                        }
                        {
                            var result =  collection.UpdateManyAsync(filter,1)"> (result.IsModifiedCountAvailable) Console.WriteLine(result.ModifiedCount);
                        }
                    }
                }
                Console.WriteLine(------------------刪除文档--------------------------------------刪除单个--------------------110);
                        {
                            collection.DeleteOne(filter);
                        }
                        {
                             collection.DeleteOneAsync(filter);
                        }
                    }
                    Console.WriteLine(------------------删除多个--------------------var filter = Builders<BsonDocument>.Filter.Gte( collection.DeleteMany(filter);
                            Console.WriteLine(result.DeletedCount);
                        }
                        {
                             collection.DeleteManyAsync(filter);
                            Console.WriteLine(result.DeletedCount);
                        }
                    }
                }
              
                Console.WriteLine(------------------大量写入--------------------var models = new WriteModel<BsonDocument>[]
                                 {
                                     new InsertOneModel<BsonDocument>(4)),56new UpdateOneModel<BsonDocument>(
                                         ),1)">$set2))),1)">new DeleteOneModel<BsonDocument>(3new ReplaceOneModel<BsonDocument>3).Add())
                                 };
                    {
                        {
                            Console.WriteLine(-------------有序批量操作-保证操作顺序-------------------);
                            collection.BulkWrite(models);
                        }
                        /*
                        {
                            Console.WriteLine("-------------无序批量操作-不保证操作顺序-------------------");
                            collection.BulkWrite(models,new BulkWriteOptions { IsOrdered = false });
                        }*/
                    }
                    {
                        Console.WriteLine("-------------有序批量操作-保证操作顺序-------------------");
                        await collection.BulkWriteAsync(models);

                        Console.WriteLine("-------------无序批量操作-不保证操作顺序-------------------");
                        await collection.BulkWriteAsync(models,new BulkWriteOptions { IsOrdered = false });
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
                         
            Console.ReadKey();            
        }
    }
    
}

4.结果

?

C#封装MongoDB

 MongoDB.Driver;
 System.Collections.Generic;
 System.Collections;
 System.Linq.Expressions;

public  MongoDBHelper
    {
        private readonly string mongoDBConnString = null;
        string databaseName = private IMongoDatabase database = bool autoCreateDb = falsebool autoCreateCollection = ;

        static MongoDBHelper()
        {
            BsonDefaults.GuidRepresentation = GuidRepresentation.Standard;
        }

        public MongoDBHelper(string mongoDBConnString,1)">string databaseName,1)">false,1)">)
        {
            this.mongoDBConnString = mongoDBConnString;
            this.databaseName = databaseName;
            this.autoCreateDb = autoCreateDb;
            this.autoCreateCollection = autoCreateCollection;
        }

        private MongoClient CreateMongoClient()
        {
            return  MongoClient(mongoDBConnString);
        }

         IMongoDatabase GetMongoDatabase()
        {
            if (database == )
            {
                MongoClient client = this.CreateMongoClient();
                if (!this.DatabaseExists(client,databaseName) && !autoCreateDb)
                {
                    throw new KeyNotFoundException(此MongoDB名称不存在:" + databaseName);
                }
            }
            database = CreateMongoClient().GetDatabase(databaseName);
            return database;
        }

        bool DatabaseExists(MongoClient client,1)"> databaseName)
        {
            
            {
                var databaseNames = client.ListDatabases().ToList().Select(db => db.GetValue().AsString);
                 databaseNames.Contains(databaseName);
            }
            true;
            }
        }

        bool CollectionExists(IMongoDatabase database,1)"> collectionName)
        {
            var options =  ListCollectionsOptions
            {
                Filter = Builders<BsonDocument>.Filter.Eq( database.ListCollections(options).ToEnumerable().Any();
        }

        private IMongoCollection<TDoc> GetMongoCollection<TDoc>(string name,MongoCollectionSettings settings = )
        {
            IMongoDatabase mongoDatabase = GetMongoDatabase();
            this.CollectionExists(mongoDatabase,name) && !autoCreateCollection)
            {
                此Collection名称不存在: name);
            }

            return mongoDatabase.GetCollection<TDoc>(name,settings);
        }

        private List<UpdateDefinition<TDoc>> BuildUpdateDefinition<TDoc>(object doc,1)"> parent)
        {
            var updateList = new List<UpdateDefinition<TDoc>>();
            var property in typeof(TDoc).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public))
            {
                var key = parent == null ? property.Name : ${parent}.{property.Name};
                if ((property.PropertyType.IsClass || property.PropertyType.IsInterface) && property.PropertyType != typeof(string) && property.GetValue(doc) != )
                {
                    if (typeof(IList).IsAssignableFrom(property.PropertyType))
                    {
                        int i = 0;
                        var subObj = property.GetValue(doc);
                        var item in subObj as IList)
                        {
                            if (item.GetType().IsClass || item.GetType().IsInterface)
                            {
                                updateList.AddRange(BuildUpdateDefinition<TDoc>(doc,${key}.{i}));
                            }
                            else
                            {
                                updateList.Add(Builders<TDoc>.Update.Set($;
                        }
                    }
                    
                    {
                        var sub in property.PropertyType.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
                        {
                            updateList.Add(Builders<TDoc>.Update.Set(${key}.{sub.Name}
                {
                    updateList.Add(Builders<TDoc>.Update.Set(key,property.GetValue(doc)));
                }

            }
             updateList;
        }


        void CreateIndex<TDoc>(IMongoCollection<TDoc> collection,1)">string[] indexFields,CreateOneIndexOptions options = if (indexFields == null) ;
            var indexKeys = Builders<TDoc>.IndexKeys;
            IndexKeysDefinition<TDoc> keys = if (indexFields.Length > )
                keys = indexKeys.Descending(indexFields[]);
            for (1; i < indexFields.Length; i++)
            {
                var strIndex = indexFields[i];
                keys = keys.Descending(strIndex);
            }
            if (keys != )
                collection.Indexes.CreateOne(new CreateIndexModel<TDoc>(keys),options);
        }


        void CreateCollectionIndex<TDoc>(string collectionName,1)">)
            => this.CreateIndex(GetMongoCollection<TDoc>(collectionName),indexFields,options);


        void CreateCollection<TDoc>(string[] indexFields = null,1)">this.CreateCollection<TDoc>((TDoc).Name,options);

        var mongoDatabase = .GetMongoDatabase();
            mongoDatabase.CreateCollection(collectionName);
            CreateIndex(this.GetMongoCollection<TDoc>public List<TDoc> Find<TDoc>(Expression<Func<TDoc,1)">bool>> filter,FindOptions options = )
            => Find<TDoc>(public List<TDoc> Find<TDoc>((collectionName).Find(filter,options).ToList();

        public List<TDoc> FindByPage<TDoc,TResult>(Expression<Func<TDoc,TResult>> keySelector,1)">int pageIndex,1)">int pageSize,1)">out int rsCount)
        {
            string collectionName = (TDoc).Name;
            return FindByPage<TDoc,TResult>(collectionName,keySelector,pageIndex,pageSize,1)">out rsCount);
        }

        var colleciton = GetMongoCollection<TDoc>(collectionName);
            rsCount = colleciton.AsQueryable().Where(filter).Count();

            int pageCount = rsCount / pageSize + ((rsCount % pageSize) > 0 ? 1 : );
            if (pageIndex > pageCount) pageIndex = pageCount;
            if (pageIndex <= 0) pageIndex = ;            
            return colleciton.AsQueryable(new AggregateOptions { AllowDiskUse = true }).Where(filter).OrderBy(keySelector).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }

        void Insert<TDoc>(TDoc doc,InsertOneOptions options = (TDoc).Name;
            Insert<TDoc>(collectionName,doc,1)">void Insert<TDoc>((collectionName);
            colleciton.InsertOne(doc,1)">void InsertMany<TDoc>(IEnumerable<TDoc> docs,InsertManyOptions options = (TDoc).Name;
            InsertMany<TDoc>void InsertMany<TDoc>((collectionName);
            colleciton.InsertMany(docs,1)">void Update<TDoc>(TDoc doc,UpdateOptions options = (collectionName);
            List<UpdateDefinition<TDoc>> updateList = BuildUpdateDefinition<TDoc>(doc,1)">);
            colleciton.UpdateOne(filter,Builders<TDoc>.Update.Combine(updateList),1)">void Update<TDoc>((TDoc).Name;
            Update<TDoc>(collectionName);
            colleciton.UpdateOne(filter,1)">void UpdateMany<TDoc>(TDoc doc,1)">(TDoc).Name;
            UpdateMany<TDoc>void UpdateMany<TDoc>();
            colleciton.UpdateMany(filter,1)">void Delete<TDoc>(Expression<Func<TDoc,DeleteOptions options = (TDoc).Name;
            Delete<TDoc>void Delete<TDoc>((collectionName);
            DeleteResult deleteResult= colleciton.DeleteOne(filter,options);
            Console.WriteLine(deleteResult.DeletedCount);
        }


        void DeleteMany<TDoc>(Expression<Func<TDoc,1)">(TDoc).Name;
            DeleteMany<TDoc>void DeleteMany<TDoc>((collectionName);
            colleciton.DeleteMany(filter,1)">void ClearCollection<TDoc>((collectionName);
            var inddexs = colleciton.Indexes.List();
            List<IEnumerable<BsonDocument>> docIndexs = new List<IEnumerable<BsonDocument>>while (inddexs.MoveNext())
            {
                docIndexs.Add(inddexs.Current);
            }
            var mongoDatabase = GetMongoDatabase();
            mongoDatabase.DropCollection(collectionName);

            CollectionExists(mongoDatabase,collectionName))
            {
                CreateCollection<TDoc>(collectionName);
            }

            if (docIndexs.Count > )
            {
                colleciton = mongoDatabase.GetCollection<TDoc>(collectionName);
                var index  docIndexs)
                {
                    foreach (IndexKeysDefinition<TDoc> indexItem  index)
                    {
                        
                        {
                            colleciton.Indexes.CreateOne((indexItem));
                        }
                        
                        { }
                    }
                }
            }

        }

    }
}

?

?测试

var mongoDbHelper = new MongoDBHelper(mongodb://127.0.0.1:27017LogDBtrue,1)">);

            mongoDbHelper.CreateCollection<SysLogInfo>(SysLog1new[] { LogDT });

            mongoDbHelper.Insert<SysLogInfo>(new SysLogInfo { LogDT = DateTime.Now,Level = Info测试消息 });

            mongoDbHelper.Find<SysLogInfo>()
                .ForEach(doc => Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(doc)));

            System.Collections.Generic.List<SysLogInfo> list = new System.Collections.Generic.List<SysLogInfo>();

            0; i < 100; i++)
            {
                list.Add(new SysLogInfo(i,DateTime.Now,1)">你好));
            }


            mongoDbHelper.InsertMany<SysLogInfo>(int rsCount = var result = mongoDbHelper.FindByPage<SysLogInfo,Object>(1,1)">20,1)"> rsCount);

            result.ForEach(doc => Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(doc)));

            mongoDbHelper.Update<SysLogInfo>(new SysLogInfo { _id = CodeError测试消息2" },t => t.LogDT >= new DateTime(1900,1)">));


            mongoDbHelper.Delete<SysLogInfo>();

            mongoDbHelper.ClearCollection<SysLogInfo>(");

?

实体类

 System.Text;

 SysLogInfo
    {
        object _id { get; set; }

        public DateTime LogDT { string Level { string Msg { ; }       

        public SysLogInfo()
        {

        }

        public SysLogInfo(object id,DateTime logDT,1)">string level,1)"> msg)
        {
            this._id = id;
            this.Msg = msg;
            this.LogDT = logDT;
            this.Level = level;
        }
    }
}

?二.Java驱动连接MongoDB

1.新建项目

?

?

?2.导入pom坐标

<dependencies>
    dependency>
        groupId>org.mongodb</artifactId>mongo-java-driverversion>3.12.1>
>

3.测试

package cn.lb.entity;


import com.mongodb.Block;
import com.mongodb.client.*;
 com.mongodb.client.result.DeleteResult;
 com.mongodb.client.result.UpdateResult;
 org.bson.Document;

 java.util.ArrayList;
 java.util.Arrays;
 java.util.List;

import static com.mongodb.client.model.Filters.* com.mongodb.client.model.Updates.inc;

 mongodbTest {

    private  static  MongoCursor<Document> cursor=;

    static void main(String[] args) {
        {
            MongoClient mongoClient= MongoClients.create("mongodb://47.100.46.200:27017");

            MongoDatabase database=mongoClient.getDatabase("mydb");

            MongoCollection<Document> collection=database.getCollection("test");

            Document doc = new Document("name","MongoDB")
                    .append("type","database")
                    .append("count",1)
                    .append("versions",Arrays.asList("v3.2","v3.0","v2.6"))
                    .append("info",1)">new Document("x",203).append("y",102));

            System.out.println("--------------插入一条------------------");

            collection.insertOne(doc);

            System.out.println("--------------插入多条------------------");

            List<Document> documentList=new ArrayList<Document>int i = 0; i < 100; i++) {
                documentList.add(new Document("i"collection.countDocuments());

            Document myDoc=collection.find().first();

            System.out.println("第一个文档:"+myDoc.toJson());

            cursor=collection.find().iterator();

            (cursor.hasNext())
            {
                System.out.println(cursor.next().toJson());
            }

            for (Document cur:collection.find())
            {
                System.out.println(cur.toJson());
            }

            System.out.println("------------过滤---------------");

            myDoc=collection.find(eq("i",71)).first();

            System.out.println(myDoc);

            Block<Document> printBlock=new Block<Document>() {
                @Override
                 apply(Document document) {
                    System.out.println(document.toString());
                }
            };

            collection.find(gt("i",50)).forEach(printBlock);


            collection.find(and(gt("i",50),lte("i",100))).forEach(printBlock);

            System.out.println("---------------更新文档-------------------");

            collection.updateOne(eq("i",10),1)">new Document("$set",1)">new Document("i",10)));

            UpdateResult updateResult=collection.updateMany(lt("i",100),inc("i",1)">));

            System.out.println(updateResult. getModifiedCount());

            System.out.println("-----------------删除文档-------------------");

            collection.deleteOne(eq("i",110));

            DeleteResult deleteResult=collection.deleteMany(gte("i",1)">));

            System.out.println(deleteResult.getDeletedCount());

            collection.createIndex());

        } (Exception ex)
        {
            ex.printStackTrace();
        }
        finally {
           if (cursor!=)
           {
               cursor.close();
           }
        }
    }
}

4.结果

?

?

?

Java封装MongoDB

导入pom坐标

?

 >
            >log4j>1.2.17>org.apache.commons>commons-lang3>3.9>

?

添加类

?

 cn.lb.util;

 com.mongodb.MongoClient;
 com.mongodb.MongoCredential;
 com.mongodb.ServerAddress;
 com.mongodb.client.FindIterable;
 com.mongodb.client.MongoCollection;
 com.mongodb.client.MongoCursor;
 com.mongodb.client.MongoDatabase;
 com.mongodb.client.model.Filters;
 org.apache.commons.lang3.StringUtils;
 org.apache.log4j.Logger;
 java.util.List;
 java.util.Map;


 MongoDBUtil {
     MongoDBUtil mongoDBUtil;

    final String PLEASE_SEND_IP = "没有传入ip或者端口号";
    final String PLEASE_INSTANCE_MONGOCLIENT = "请实例化MongoClient"final String PLEASE_SEND_MONGO_REPOSITORY = "请指定要删除的mongo库"final String DELETE_MONGO_REPOSITORY_EXCEPTION = "删除mongo库异常"final String DELETE_MONGO_REPOSITORY_SUCCESS = "批量删除mongo库成功"final String NOT_DELETE_MONGO_REPOSITORY = "未删除mongo库"final String DELETE_MONGO_REPOSITORY = "成功删除mongo库:"final String CREATE_MONGO_COLLECTION_NOTE = "请指定要创建的库"final String NO_THIS_MONGO_DATABASE = "未找到指定mongo库"final String CREATE_MONGO_COLLECTION_SUCCESS = "创建mongo库成功"final String CREATE_MONGO_COLLECTION_EXCEPTION = "创建mongo库错误"final String NOT_CREATE_MONGO_COLLECTION = "未创建mongo库collection"final String CREATE_MONGO_COLLECTION_SUCH = "创建mongo库collection:"final String NO_FOUND_MONGO_COLLECTION = "未找到mongo库collection"final String INSERT_DOCUMEN_EXCEPTION = "插入文档失败"final String INSERT_DOCUMEN_SUCCESSS = "插入文档成功";


    final Logger logger = Logger.getLogger(MongoDBUtil.);

     MongoDBUtil(){

    }

     SingleHolder{
        static MongoDBUtil mongoDBUtil =  MongoDBUtil();
    }

     MongoDBUtil instance(){

         SingleHolder.mongoDBUtil;
    }

     MongoDBUtil getMongoDBUtilInstance(){
        if(mongoDBUtil == ){
             MongoDBUtil();
        }
         mongoDBUtil;
    }

    /**
     * 获取mongoDB连接
     * @param host
     *  port
     * @return
     */
     MongoClient getMongoConnect(String host,Integer port){

        if(StringUtils.isBlank(host) || null == port){
            logger.error(PLEASE_SEND_IP);
            ;
        }

         MongoClient(host,port);
    }


    
     * 批量删除mongo库
     *  mongoClient
     *  dbNames
     *  String bulkDropDataBase(MongoClient mongoClient,String...dbNames){

        if(null == mongoClient)  PLEASE_INSTANCE_MONGOCLIENT;

        null==dbNames || dbNames.length==0 PLEASE_SEND_MONGO_REPOSITORY;
        }
         {
            Arrays.asList(dbNames).forEach(dbName -> mongoClient.dropDatabase(dbName));
            logger.info(DELETE_MONGO_REPOSITORY_SUCCESS);
        } (Exception e){
            e.printStackTrace();
            logger.error(DELETE_MONGO_REPOSITORY_EXCEPTION);
        }
        return dbNames == null ? NOT_DELETE_MONGO_REPOSITORY:DELETE_MONGO_REPOSITORY + String.join(","
     * 创建指定database的collection
     *  dbName
     *  collections
     *  String createCollections(MongoClient mongoClient,String dbName,String...collections){

        null==collections || collections.length==0 CREATE_MONGO_COLLECTION_NOTE;
        }

        MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName);
        null == mongoDatabase)  NO_THIS_MONGO_DATABASE;

         {
            Arrays.asList(collections).forEach(collection ->  mongoDatabase.createCollection(collection));
            logger.info(CREATE_MONGO_COLLECTION_SUCCESS);
            return collections == null ? NOT_CREATE_MONGO_COLLECTION:CREATE_MONGO_COLLECTION_SUCH + String.join(",collections);
        } (Exception e){
            e.printStackTrace();
            logger.error(CREATE_MONGO_COLLECTION_EXCEPTION);
        }

        ;
    }

    
     * 获取MongoCollection
     *  collection
     * public MongoCollection<Document> getMongoCollection(MongoClient mongoClient,String collection){

        if(StringUtils.isBlank(dbName)) if(StringUtils.isBlank(collection)) ;

        MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName);

        MongoCollection<Document> collectionDocuments = mongoDatabase.getCollection(collection);

        null == collectionDocuments)  collectionDocuments;
    }

    
     * 获取到MongoClient
     *  ip
     *  userName
     *  psw
     * @returnMongoClient
     static MongoClient getMongoClientByCredential(String ip,1)"> port,String userName,String psw){
        ServerAddress serverAddress =  ServerAddress(ip,port);
        List<ServerAddress> addrs = new ArrayList<ServerAddress>();
        addrs.add(serverAddress);

        MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
        MongoCredential credential = MongoCredential.createScramSha1Credential(userName,dbName,psw.toCharArray());
        List<MongoCredential> credentials = new ArrayList<MongoCredential>();
        credentials.add(credential);

        通过连接认证获取MongoDB连接
        MongoClient mongoClient =  MongoClient(addrs,credentials);
         mongoClient;
    }


    
     * 插入文档数据
     *  mongoCollection
     *  params
     void insertDoucument(final MongoCollection<Document> mongoCollection,1)">final Map<String,Object> params){
         mongoCollection) {
            logger.info(NO_FOUND_MONGO_COLLECTION);
             {
            Document document =  Document();
            params.keySet().stream().forEach(field -> document.append(field,params.get(field)));

            List<Document> documents = new ArrayList<>();
            documents.add(document);
            mongoCollection.insertMany(documents);
            logger.info(INSERT_DOCUMEN_SUCCESSS);
        } (Exception e){
            e.printStackTrace();
            logger.error(INSERT_DOCUMEN_EXCEPTION);
        }
    }

    
     * 更新文档
     *  conditionParams
     *  updateParams
     public  void updateDocument( conditionParams,Object> updateParams,1)">final boolean MultiUpdate
    ){

        null == mongoCollection) null == conditionParams) null == updateParams) ;


        Document conditonDocument =  Document();
        conditionParams.keySet().stream().filter(p -> null != p).forEach(o -> {
            conditonDocument.append(o,conditionParams.get(o));
        });


        Document updateDocument =  Document();
        updateParams.keySet().stream().filter(p ->  {
            updateDocument.append(o,updateParams.get(o));
        });
        UpdateResult updateResult = if (MultiUpdate){是否批量更新
            updateResult = mongoCollection.updateMany(conditonDocument,1)">new Document("$set" {
            updateResult = mongoCollection.updateOne(conditonDocument,updateDocument));
        }
        System.out.println("修改了:"+updateResult.getModifiedCount()+" 条数据 ");

    }

    
     *条件 删除文档 是否多条删除
     *  multiple
     * long deleteDocument( multiple,1)"> conditionParams){

        return 0;

        Document document =  Document();

        conditionParams.keySet().stream().filter(p ->  {
            document.append(o,conditionParams.get(o));
        });

        (multiple) {
             mongoCollection.deleteMany(document).getDeletedCount();
        }

        删除文档第一条
         mongoCollection.deleteOne(document).getDeletedCount();
    }

    
     * 查询文档 带条件、范围查找、排序、分页
     *  limit
     *  skip
     *  sortParams
     public FindIterable<Document> queryDocument(final String op,1)">final String compareField,Integer> gtLtOrOtherParams,Object> sortParams,1)">final Integer skip,1)">final Integer limit
    ){

        ;

        FindIterable<Document> findIterable = mongoCollection.find();
        Document conditionDocument =  Document();
        Document compareDocument =  Document();

        null != conditionParams && null != findIterable){

            conditionParams.forEach((k,v) ->{
                 (StringUtils.isNotBlank(k)) {
                    conditionDocument.append(k,v);
                }
            });

            findIterable = findIterable.filter(conditionDocument);

            MongoCursor<Document> mongoCursor = findIterable.iterator();
            (mongoCursor.hasNext()){
                System.out.println("条件过滤  -->"+mongoCursor.next());
            }
        }

        null != findIterable &&  gtLtOrOtherParams){

            Document gtOrLtDoc =  Document();
            gtLtOrOtherParams.forEach((k,1)"> {
                (StringUtils.isNotBlank(k)) gtOrLtDoc.append(k,v);
            });

            compareDocument =  Document(compareField,gtOrLtDoc);
            findIterable = findIterable.filter( (StringUtils.isNotBlank(op)){
            if ("and".equals(op)){
                findIterable = mongoCollection.find(Filters.and(conditionDocument,compareDocument));
            }else if("or" mongoCollection.find(Filters.or(conditionDocument,1)">if("not".equals(op)){排除范围
                findIterable =else{默认是AND查询
            findIterable = findIterable.iterator();
        (mongoCursor3.hasNext()){
            System.out.println(op+"过滤  -->"+mongoCursor3.next());
        }

         sortParams){
            Document sortDocument =  Document();
            sortParams.forEach((k,1)"> (StringUtils.isNotBlank(k)) {
                    sortDocument.append(k,1)"> findIterable.sort(sortDocument);

            MongoCursor<Document> mongoCursor2 =(mongoCursor2.hasNext()){
                System.out.println("排序  -->"+mongoCursor2.next());
            }
        }



         limit){
            findIterable = findIterable.limit(limit);
        }
         skip){
            findIterable = findIterable.skip(skip);
        }

         findIterable;
    }


    
     * in查询
     * public FindIterable<Document>  queryDocumentIn( list
    ){

        ;
        FindIterable<Document> findIterable = mongoCollection.find(new Document(field,1)">new Document("$in"
     * 全文查询
     * public FindIterable<Document>  queryDocument(final MongoCollection<Document> mongoCollection
    ){
        ;
        FindIterable<Document> findIterable = mongoCollection.find();
        
     * 查询文档 简单条件查询
     *  conditionParams
    ){

         mongoCollection.find();

        null == conditionParams || null == findIterable)  findIterable;

        Document document =  Document();
        conditionParams.forEach((k,v)->{
             (StringUtils.isNotBlank(k)) {
                document.append(k,v);
            }
        });
        findIterable = findIterable.filter(document);

         findIterable;

    }


    
     * 用于输出部分的列信息
     *  documents
     void printDocuments(FindIterable<Document> documents,String[] fields) {
        if (fields != null && fields.length > 0) {
            int num = 0 (Document d : documents) {
                StringBuilder stringBuilder =  StringBuilder();
                int i = 0; i < fields.length; i++) {
                    if(fields[i].equals("catm")){

                    }
                    stringBuilder.append(fields[i] + ": "+d.getString(fields[i])+" ");
                }
                System.out.println("第" + (++num) + "条数据: " + stringBuilder);

            }
        } (Document d : documents) {
                System.out.println(d.toString());
            }
        }
    }

    
     * 用于输出所有的列信息
     *  documents) {
         (Document d : documents) {
            System.out.println("第" + (++num) + "条数据: " + d.toString());
        }
    }

}

?

?

C#API参考地址:https://api.mongodb.com/csharp/2.2/html/N_MongoDB_Driver.htm

C#驱动连接文档地址:http://mongodb.github.io/mongo-csharp-driver/2.10/getting_started/quick_tour/

Java驱动连接文档地址:http://mongodb.github.io/mongo-java-driver/3.12/driver/getting-started/installation/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读