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

一.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/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


文章浏览阅读552次。com.mongodb.MongoQueryException: Query failed with error code 292 and error message 'Executor error during find command :: caused by :: Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting.' on server 11.51.141.63:27017 _mongodb 大文件 下载失败
文章浏览阅读635次,点赞9次,收藏8次。MongoDB 是一种 NoSQL 数据库,它将每个数据存储为一个文档,这里的文档类似于 JSON/BSON 对象,具体数据结构由键值(key/value)对组成。
文章浏览阅读2.1k次。和。_mongodb 日期类型
文章浏览阅读1.7k次。Scalestack等客户期待使用MongoDB Atlas Vector Search和Amazon Bedrock构建下一代应用程序
文章浏览阅读970次。SpringBoot整合中间件mongodb、ES_springboot3 elasticsearch json数据
文章浏览阅读673次。MongoDB 简介_尚医通sql
文章浏览阅读1k次,点赞8次,收藏9次。官网下载MongoDB安装包后进行解压(因了解并不深入,故暂不进行详细说明,自行查找其他安装方法,后期了解深入后将进行该教程的完善)在bin目录下使用命令启动:./mongod --config …/mongodb.conf。该文章任然处于完善中,如果存在错误遗漏的地方,欢迎私信联系。安装相关的nuget包后即可通过以下方法连接数据。YX9010_0@的第二十篇文章。
文章浏览阅读1.2k次,点赞17次,收藏26次。社交场景, 使用 MongoDB 存储存储用户信息, 以及用户发表的朋友圈信息, 通过地理位置索引实现附近的人, 地点等功能.游戏场景, 使用 MongoDB 存储游戏用户信息, 用户的装备, 积分等直接以内嵌文档的形式存储, 方便查询, 高效率存储和访问.物流场景, 使用 MongoDB 存储订单信息, 订单状态在运送过程中会不断更新, 以 MongoDB 内嵌数组的形式来存储, 一次查询就能将订单所有的变更读取出来.物联网场景, 使用 MongoDB 存储所有接入的智能设备信息, 以及设备汇报的日
文章浏览阅读686次。您可以使用 update_one() 方法来更新 MongoDB 中调用的记录或文档。update_one() 方法的第一个参数是 query 对象,用于定义要更新的文档。注释:如果查询找到多个记录,则仅更新第一个匹配项。第二个参数是定义文档新值的对象。_python 更新 mongodb 数据
文章浏览阅读1.3k次。首先来学习一下nosql这里安装就不进行介绍 只记录一下让自己了解mongodb。_nosql注入
文章浏览阅读4.1k次,点赞8次,收藏7次。在data的目录下,创建一个db文件。因为启动MongoDB服务之前必须创建数据库文件的存放文件夹,否则命令不会自动创建,而且不能启动成功。第一步:安装时,Custom是指可以自定义安装路径,然后傻瓜式安装即可(注意:先不要安装图形化工具,否则安装时间会特别长):如果要想连接成功,必须要开服务,即mongod -dbpath C:MongoDBdatadb的cmd要一直开着。然后回车,ctrl+F输入port找到端口号,一般为:27017。打开命令行,然后找到bin文件地址,并输入。_mongodb windows安装
文章浏览阅读5.1k次,点赞3次,收藏43次。详细介绍MongoDB数据库的基本知识,安装方法,基本操作,_mongodb数据库
文章浏览阅读3.2k次。安装教程翻看以往文章。_navicat 连接mongodb
文章浏览阅读426次,点赞9次,收藏12次。win10开放端口:https://blog.csdn.net/m0_43605481/article/details/119255256。我的是阿里云服务器,所以直接在安全组中加入规则,端口范围:27017,授权对象:0.0.0.0。windows在mongodb安装文件夹的bin文件夹中的mongod.cfg。数据库名字是test,打算创建一个用户,账号aaa,密码bbb,权限readWrite。因为该用户是创建在test数据库的,所以在最后要加上test。O了,然后恢复了test的数据。
文章浏览阅读1.1k次。聚合操作主要用于处理数据并返回计算结果。聚合操作将来自多个文档的值组合在一起,按条件分组后,再进行一系列操作(如求和、平均值、最大值、最小值)以返回单个结果。MongoDB的聚合查询​聚合是MongoDB的高级查询语言,它允许我们通过转化合并由多个文档的数据来生成新的在单个文档里不存在的文档信息。MongoDB中聚合(aggregate)主要用于处理数据(例如分组统计平均值、求和、最大值等),并返回计算后的数据结果,有点类似sql语句中的count(*)、groupby。..._如何将几个db的数据统整在一起做查询
文章浏览阅读680次,点赞7次,收藏8次。(2)application.properties配置文件。(4)UserService类。(5)测试和测试结果。
文章浏览阅读1k次,点赞17次,收藏25次。Studio 3T 2023.9 (macOS, Linux, Windows) - MongoDB 的专业 GUI、IDE 和 客户端,支持自然语言查询_mongodb客户端
文章浏览阅读1.1k次,点赞32次,收藏27次。插件式的存储引擎架构可以实现 Server 层和存储引擎层的解耦,可以支持多种存储引擎,如 MySQL 既可以支持 B-Tree 结构的 InnoDB 存储引擎,还可以支持 LSM 结构的 RocksDB 存储引擎。MongoDB 中的记录就是一个 BSON 文档,它是由键值对组成的数据结构,类似于 JSON 对象,是 MongoDB 中的基本数据单元。的简称,是 JSON 文档的二进制表示,支持将文档和数组嵌入到其他文档和数组中,还包含允许表示不属于 JSON 规范的数据类型的扩展。
文章浏览阅读5.1k次,点赞6次,收藏96次。本文设计了一种基于智能室内温度控制的自动调速风扇。以STM32系列单片机为核心主控板,通过程序代码驱动和使用温度传感器模块实现对环境温度的实时监测,并可以实时显示环境温度。同时,可以设置温度检测的上下警告值,根据需求自行调节。_stm32 温控风扇
文章浏览阅读898次,点赞13次,收藏21次。在MongoDB中,我们使用find()和find_one()方法来在集合中查找数据,就像在MySQL数据库中使用SELECT语句来在表中查找数据一样。_pymongo find_one