MongoDB系列: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; using System.Linq; using MongoDB.Bson; using 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("foo"); var collection = database.GetCollection<BsonDocument>("bar"); Console.WriteLine("-----------------添加文档--------------------"); { var document = new BsonDocument { { "name", "MongoDB" }, { "type", "Database" }, { "count", 1 }, { "info", new BsonDocument { { "x", 203 }, { "y", 102 } }} }; await collection.InsertOneAsync(document);//异步 //collection.InsertOne(document); var documents = Enumerable.Range(0, 100).Select(i => new BsonDocument("i", i)); //collection.InsertMany(documents); await collection.InsertManyAsync(documents); } Console.WriteLine("------------------统计文档--------------------"); { var count = collection.CountDocuments(new BsonDocument()); var asyncCount = await collection.CountDocumentsAsync(new BsonDocument()); Console.WriteLine(count); Console.WriteLine(asyncCount); } Console.WriteLine("-----------------查询文档--------------------"); { Console.WriteLine("------------------查询一个--------------------"); { var document = collection.Find(new BsonDocument()).FirstOrDefault(); Console.WriteLine(document.ToString()); var asyncDocument = await collection.Find(new BsonDocument()).FirstOrDefaultAsync(); Console.WriteLine(asyncDocument.ToString()); } Console.WriteLine("------------------查询多个--------------------"); { var documentList = collection.Find(new BsonDocument()).ToList(); documentList.ForEach(d => Console.WriteLine(d.ToString())); var asyncDocumentList =await collection.Find(new BsonDocument()).ToListAsync(); await collection.Find(new BsonDocument()).ForEachAsync(d => Console.WriteLine(d)); } { var cursor = collection.Find(new BsonDocument()).ToCursor(); foreach (var document in cursor.ToEnumerable()) { Console.WriteLine(document); } } } { { var filter = Builders<BsonDocument>.Filter.Eq("i", 71); { var document = collection.Find(filter).First(); Console.WriteLine(document); } { var document = await collection.Find(filter).FirstAsync(); Console.WriteLine(document); } } Console.WriteLine("------------------过滤文档--------------------"); { var filter = Builders<BsonDocument>.Filter.Gt("i", 50); { var cursor = collection.Find(filter).ToCursor(); foreach (var document in cursor.ToEnumerable()) { Console.WriteLine(document); } } { await collection.Find(filter).ForEachAsync(document => Console.WriteLine(document)); } } { var filterBuilder = Builders<BsonDocument>.Filter; var filter = filterBuilder.Gt("i", 50) & filterBuilder.Lte("i", 100); { var cursor = collection.Find(filter).ToCursor(); foreach (var document in cursor.ToEnumerable()) { Console.WriteLine(document); } } { await collection.Find(filter).ForEachAsync(document => Console.WriteLine(document)); } } } Console.WriteLine("------------------排序文档--------------------"); { var filter = Builders<BsonDocument>.Filter.Exists("i"); var sort = Builders<BsonDocument>.Sort.Descending("i"); { var document = collection.Find(filter).Sort(sort).First(); } { var document = await collection.Find(filter).Sort(sort).FirstAsync(); } } Console.WriteLine("------------------过滤文档--------------------"); { var projection = Builders<BsonDocument>.Projection.Exclude("_id"); { var document = collection.Find(new BsonDocument()).Project(projection).First(); Console.WriteLine(document.ToString()); } { var document = await collection.Find(new BsonDocument()).Project(projection).FirstAsync(); Console.WriteLine(document); } } Console.WriteLine("------------------更新文档--------------------"); { Console.WriteLine("------------------更新一个--------------------"); { var filter = Builders<BsonDocument>.Filter.Eq("i", 10); var update = Builders<BsonDocument>.Update.Set("i", 10); { collection.UpdateOne(filter, update); } { await collection.UpdateOneAsync(filter, update); } } Console.WriteLine("------------------更新多个--------------------"); { var filter = Builders<BsonDocument>.Filter.Lt("i", 100); var update = Builders<BsonDocument>.Update.Inc("i", 100); { var result = collection.UpdateMany(filter, update); if (result.IsModifiedCountAvailable) Console.WriteLine(result.ModifiedCount); } { var result = await collection.UpdateManyAsync(filter, update); if (result.IsModifiedCountAvailable) Console.WriteLine(result.ModifiedCount); } } } Console.WriteLine("------------------刪除文档--------------------"); { Console.WriteLine("------------------刪除单个--------------------"); { var filter = Builders<BsonDocument>.Filter.Eq("i", 110); { collection.DeleteOne(filter); } { await collection.DeleteOneAsync(filter); } } Console.WriteLine("------------------删除多个--------------------"); { var filter = Builders<BsonDocument>.Filter.Gte("i", 100); { var result = collection.DeleteMany(filter); Console.WriteLine(result.DeletedCount); } { var result = await collection.DeleteManyAsync(filter); Console.WriteLine(result.DeletedCount); } } } Console.WriteLine("------------------大量写入--------------------"); { 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)) }; { { 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
using MongoDB.Driver; using MongoDB.Bson; using System; using System.Collections.Generic; using System.Linq; using System.Collections; using System.Linq.Expressions; namespace MongoDBDriverDemo { public class MongoDBHelper { private readonly string mongoDBConnString = null; private readonly string databaseName = null; private IMongoDatabase database = null; private readonly bool autoCreateDb = false; private readonly bool autoCreateCollection = false; static MongoDBHelper() { BsonDefaults.GuidRepresentation = GuidRepresentation.Standard; } public MongoDBHelper(string mongoDBConnString, string databaseName, bool autoCreateDb = false, bool autoCreateCollection = false) { this.mongoDBConnString = mongoDBConnString; this.databaseName = databaseName; this.autoCreateDb = autoCreateDb; this.autoCreateCollection = autoCreateCollection; } private MongoClient CreateMongoClient() { return new MongoClient(mongoDBConnString); } private IMongoDatabase GetMongoDatabase() { if (database == null) { MongoClient client = this.CreateMongoClient(); if (!this.DatabaseExists(client, databaseName) && !autoCreateDb) { throw new KeyNotFoundException("此MongoDB名称不存在:" + databaseName); } } database = CreateMongoClient().GetDatabase(databaseName); return database; } private bool DatabaseExists(MongoClient client, string databaseName) { try { var databaseNames = client.ListDatabases().ToList().Select(db => db.GetValue("name").AsString); return databaseNames.Contains(databaseName); } catch { return true; } } private bool CollectionExists(IMongoDatabase database, string collectionName) { var options = new ListCollectionsOptions { Filter = Builders<BsonDocument>.Filter.Eq("name", collectionName) }; return database.ListCollections(options).ToEnumerable().Any(); } private IMongoCollection<TDoc> GetMongoCollection<TDoc>(string name, MongoCollectionSettings settings = null) { IMongoDatabase mongoDatabase = GetMongoDatabase(); if (!this.CollectionExists(mongoDatabase, name) && !autoCreateCollection) { throw new KeyNotFoundException("此Collection名称不存在:" + name); } return mongoDatabase.GetCollection<TDoc>(name, settings); } private List<UpdateDefinition<TDoc>> BuildUpdateDefinition<TDoc>(object doc, string parent) { var updateList = new List<UpdateDefinition<TDoc>>(); foreach (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) != null) { if (typeof(IList).IsAssignableFrom(property.PropertyType)) { int i = 0; var subObj = property.GetValue(doc); foreach (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($"{key}.{i}", item)); } i++; } } else { var subObj = property.GetValue(doc); foreach (var sub in property.PropertyType.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)) { updateList.Add(Builders<TDoc>.Update.Set($"{key}.{sub.Name}", sub.GetValue(subObj))); } } } else { updateList.Add(Builders<TDoc>.Update.Set(key, property.GetValue(doc))); } } return updateList; } private void CreateIndex<TDoc>(IMongoCollection<TDoc> collection, string[] indexFields, CreateOneIndexOptions options = null) { if (indexFields == null) return; var indexKeys = Builders<TDoc>.IndexKeys; IndexKeysDefinition<TDoc> keys = null; if (indexFields.Length > 0) keys = indexKeys.Descending(indexFields[0]); for (int i = 1; i < indexFields.Length; i++) { var strIndex = indexFields[i]; keys = keys.Descending(strIndex); } if (keys != null) collection.Indexes.CreateOne(new CreateIndexModel<TDoc>(keys), options); } public void CreateCollectionIndex<TDoc>(string collectionName, string[] indexFields, CreateOneIndexOptions options = null) => this.CreateIndex(GetMongoCollection<TDoc>(collectionName), indexFields, options); public void CreateCollection<TDoc>(string[] indexFields = null, CreateOneIndexOptions options = null) => this.CreateCollection<TDoc>(typeof(TDoc).Name, indexFields, options); public void CreateCollection<TDoc>(string collectionName, string[] indexFields = null, CreateOneIndexOptions options = null) { var mongoDatabase = this.GetMongoDatabase(); mongoDatabase.CreateCollection(collectionName); CreateIndex(this.GetMongoCollection<TDoc>(collectionName), indexFields, options); } public List<TDoc> Find<TDoc>(Expression<Func<TDoc, bool>> filter, FindOptions options = null) => Find<TDoc>(typeof(TDoc).Name, filter, options); public List<TDoc> Find<TDoc>(string collectionName, Expression<Func<TDoc, bool>> filter, FindOptions options = null) => this.GetMongoCollection<TDoc>(collectionName).Find(filter, options).ToList(); public List<TDoc> FindByPage<TDoc, TResult>(Expression<Func<TDoc, bool>> filter, Expression<Func<TDoc, TResult>> keySelector, int pageIndex, int pageSize, out int rsCount) { string collectionName = typeof(TDoc).Name; return FindByPage<TDoc, TResult>(collectionName, filter, keySelector, pageIndex, pageSize, out rsCount); } public List<TDoc> FindByPage<TDoc, TResult>(string collectionName, Expression<Func<TDoc, bool>> filter, Expression<Func<TDoc, TResult>> keySelector, int pageIndex, int pageSize, out int rsCount) { var colleciton = GetMongoCollection<TDoc>(collectionName); rsCount = colleciton.AsQueryable().Where(filter).Count(); int pageCount = rsCount / pageSize + ((rsCount % pageSize) > 0 ? 1 : 0); if (pageIndex > pageCount) pageIndex = pageCount; if (pageIndex <= 0) pageIndex = 1; return colleciton.AsQueryable(new AggregateOptions { AllowDiskUse = true }).Where(filter).OrderBy(keySelector).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } public void Insert<TDoc>(TDoc doc, InsertOneOptions options = null) { string collectionName = typeof(TDoc).Name; Insert<TDoc>(collectionName, doc, options); } public void Insert<TDoc>(string collectionName, TDoc doc, InsertOneOptions options = null) { var colleciton = GetMongoCollection<TDoc>(collectionName); colleciton.InsertOne(doc, options); } public void InsertMany<TDoc>(IEnumerable<TDoc> docs, InsertManyOptions options = null) { string collectionName = typeof(TDoc).Name; InsertMany<TDoc>(collectionName, docs, options); } public void InsertMany<TDoc>(string collectionName, IEnumerable<TDoc> docs, InsertManyOptions options = null) { var colleciton = GetMongoCollection<TDoc>(collectionName); colleciton.InsertMany(docs, options); } public void Update<TDoc>(TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateOptions options = null) { string collectionName = typeof(TDoc).Name; var colleciton = GetMongoCollection<TDoc>(collectionName); List<UpdateDefinition<TDoc>> updateList = BuildUpdateDefinition<TDoc>(doc, null); colleciton.UpdateOne(filter, Builders<TDoc>.Update.Combine(updateList), options); } public void Update<TDoc>(string collectionName, TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateOptions options = null) { var colleciton = GetMongoCollection<TDoc>(collectionName); List<UpdateDefinition<TDoc>> updateList = BuildUpdateDefinition<TDoc>(doc, null); colleciton.UpdateOne(filter, Builders<TDoc>.Update.Combine(updateList), options); } public void Update<TDoc>(TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateDefinition<TDoc> updateFields, UpdateOptions options = null) { string collectionName = typeof(TDoc).Name; Update<TDoc>(collectionName, doc, filter, updateFields, options); } public void Update<TDoc>(string collectionName, TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateDefinition<TDoc> updateFields, UpdateOptions options = null) { var colleciton = GetMongoCollection<TDoc>(collectionName); colleciton.UpdateOne(filter, updateFields, options); } public void UpdateMany<TDoc>(TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateOptions options = null) { string collectionName = typeof(TDoc).Name; UpdateMany<TDoc>(collectionName, doc, filter, options); } public void UpdateMany<TDoc>(string collectionName, TDoc doc, Expression<Func<TDoc, bool>> filter, UpdateOptions options = null) { var colleciton = GetMongoCollection<TDoc>(collectionName); List<UpdateDefinition<TDoc>> updateList = BuildUpdateDefinition<TDoc>(doc, null); colleciton.UpdateMany(filter, Builders<TDoc>.Update.Combine(updateList), options); } public void Delete<TDoc>(Expression<Func<TDoc, bool>> filter, DeleteOptions options = null) { string collectionName = typeof(TDoc).Name; Delete<TDoc>(collectionName, filter, options); } public void Delete<TDoc>(string collectionName, Expression<Func<TDoc, bool>> filter, DeleteOptions options = null) { var colleciton = GetMongoCollection<TDoc>(collectionName); DeleteResult deleteResult= colleciton.DeleteOne(filter, options); Console.WriteLine(deleteResult.DeletedCount); } public void DeleteMany<TDoc>(Expression<Func<TDoc, bool>> filter, DeleteOptions options = null) { string collectionName = typeof(TDoc).Name; DeleteMany<TDoc>(collectionName, filter, options); } public void DeleteMany<TDoc>(string collectionName, Expression<Func<TDoc, bool>> filter, DeleteOptions options = null) { var colleciton = GetMongoCollection<TDoc>(collectionName); colleciton.DeleteMany(filter, options); } public void ClearCollection<TDoc>(string collectionName) { var colleciton = GetMongoCollection<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); if (!CollectionExists(mongoDatabase, collectionName)) { CreateCollection<TDoc>(collectionName); } if (docIndexs.Count > 0) { colleciton = mongoDatabase.GetCollection<TDoc>(collectionName); foreach (var index in docIndexs) { foreach (IndexKeysDefinition<TDoc> indexItem in index) { try { colleciton.Indexes.CreateOne(new CreateIndexModel<TDoc>(indexItem)); } catch { } } } } } } }
测试
var mongoDbHelper = new MongoDBHelper("mongodb://127.0.0.1:27017", "LogDB",true,true); mongoDbHelper.CreateCollection<SysLogInfo>("SysLog1", new[] { "LogDT" }); mongoDbHelper.Insert<SysLogInfo>("SysLog1", new SysLogInfo { LogDT = DateTime.Now, Level = "Info", Msg = "测试消息" }); mongoDbHelper.Find<SysLogInfo>("SysLog1", t => t.Level == "Info") .ForEach(doc => Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(doc))); System.Collections.Generic.List<SysLogInfo> list = new System.Collections.Generic.List<SysLogInfo>(); for (int i = 0; i < 100; i++) { list.Add(new SysLogInfo(i, DateTime.Now, "Info", "你好")); } mongoDbHelper.InsertMany<SysLogInfo>("SysLog1", list); int rsCount = 0; var result = mongoDbHelper.FindByPage<SysLogInfo, Object>("SysLog1", t => t.Level == "Info", t => t._id, 1, 20, out rsCount); result.ForEach(doc => Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(doc))); mongoDbHelper.Update<SysLogInfo>("SysLog1", new SysLogInfo { _id = "Code", LogDT = DateTime.Now, Level = "Error", Msg = "测试消息2" }, t => t.LogDT >= new DateTime(1900, 1, 1)); mongoDbHelper.Delete<SysLogInfo>("SysLog1", t => t.Level == "Info"); mongoDbHelper.ClearCollection<SysLogInfo>("SysLog1");
实体类
using System; using System.Collections.Generic; using System.Text; namespace MongoDBDriverDemo { public class SysLogInfo { public object _id { get; set; } public DateTime LogDT { get; set; } public string Level { get; set; } public string Msg { get; set; } public SysLogInfo() { } public SysLogInfo(object id, DateTime logDT,string level,string msg) { this._id = id; this.Msg = msg; this.LogDT = logDT; this.Level = level; } } }
二.Java驱动连接MongoDB
1.新建项目
2.导入pom坐标
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.1</version> </dependency> </dependencies>
3.测试
package cn.lb.entity; import com.mongodb.Block; import com.mongodb.client.*; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; import org.bson.Document; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.mongodb.client.model.Filters.*; import static com.mongodb.client.model.Updates.inc; public class mongodbTest { private static MongoCursor<Document> cursor=null; public static void main(String[] args) { try{ 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", new Document("x", 203).append("y", 102)); System.out.println("--------------插入一条------------------"); collection.insertOne(doc); System.out.println("--------------插入多条------------------"); List<Document> documentList=new ArrayList<Document>(); for (int i = 0; i < 100; i++) { documentList.add(new Document("i",i)); } collection.insertMany(documentList); System.out.println("文档总数:"+collection.countDocuments()); Document myDoc=collection.find().first(); System.out.println("第一个文档:"+myDoc.toJson()); cursor=collection.find().iterator(); while(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 public void 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),new Document("$set",new Document("i",10))); UpdateResult updateResult=collection.updateMany(lt("i",100),inc("i",100)); System.out.println(updateResult. getModifiedCount()); System.out.println("-----------------删除文档-------------------"); collection.deleteOne(eq("i",110)); DeleteResult deleteResult=collection.deleteMany(gte("i",100)); System.out.println(deleteResult.getDeletedCount()); collection.createIndex(new Document("i",1)); }catch (Exception ex) { ex.printStackTrace(); } finally { if (cursor!=null) { cursor.close(); } } } }
4.结果
Java封装MongoDB
导入pom坐标
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency> </dependencies>
添加类
package cn.lb.util; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.mongodb.client.result.UpdateResult; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.bson.Document; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; public class MongoDBUtil { private static MongoDBUtil mongoDBUtil; private static final String PLEASE_SEND_IP = "没有传入ip或者端口号"; private static final String PLEASE_INSTANCE_MONGOCLIENT = "请实例化MongoClient"; private static final String PLEASE_SEND_MONGO_REPOSITORY = "请指定要删除的mongo库"; private static final String DELETE_MONGO_REPOSITORY_EXCEPTION = "删除mongo库异常"; private static final String DELETE_MONGO_REPOSITORY_SUCCESS = "批量删除mongo库成功"; private static final String NOT_DELETE_MONGO_REPOSITORY = "未删除mongo库"; private static final String DELETE_MONGO_REPOSITORY = "成功删除mongo库:"; private static final String CREATE_MONGO_COLLECTION_NOTE = "请指定要创建的库"; private static final String NO_THIS_MONGO_DATABASE = "未找到指定mongo库"; private static final String CREATE_MONGO_COLLECTION_SUCCESS = "创建mongo库成功"; private static final String CREATE_MONGO_COLLECTION_EXCEPTION = "创建mongo库错误"; private static final String NOT_CREATE_MONGO_COLLECTION = "未创建mongo库collection"; private static final String CREATE_MONGO_COLLECTION_SUCH = "创建mongo库collection:"; private static final String NO_FOUND_MONGO_COLLECTION = "未找到mongo库collection"; private static final String INSERT_DOCUMEN_EXCEPTION = "插入文档失败"; private static final String INSERT_DOCUMEN_SUCCESSS = "插入文档成功"; private static final Logger logger = Logger.getLogger(MongoDBUtil.class); private MongoDBUtil(){ } private static class SingleHolder{ private static MongoDBUtil mongoDBUtil = new MongoDBUtil(); } public static MongoDBUtil instance(){ return SingleHolder.mongoDBUtil; } public static MongoDBUtil getMongoDBUtilInstance(){ if(mongoDBUtil == null){ return new MongoDBUtil(); } return mongoDBUtil; } /** * 获取mongoDB连接 * @param host * @param port * @return */ public MongoClient getMongoConnect(String host,Integer port){ if(StringUtils.isBlank(host) || null == port){ logger.error(PLEASE_SEND_IP); return null; } return new MongoClient(host, port); } /** * 批量删除mongo库 * @param mongoClient * @param dbNames * @return */ public String bulkDropDataBase(MongoClient mongoClient,String...dbNames){ if(null == mongoClient) return PLEASE_INSTANCE_MONGOCLIENT; if(null==dbNames || dbNames.length==0){ return PLEASE_SEND_MONGO_REPOSITORY; } try { Arrays.asList(dbNames).forEach(dbName -> mongoClient.dropDatabase(dbName)); logger.info(DELETE_MONGO_REPOSITORY_SUCCESS); }catch (Exception e){ e.printStackTrace(); logger.error(DELETE_MONGO_REPOSITORY_EXCEPTION); } return dbNames == null ? NOT_DELETE_MONGO_REPOSITORY:DELETE_MONGO_REPOSITORY + String.join(",",dbNames); } /** * 创建指定database的collection * @param mongoClient * @param dbName * @param collections * @return */ public String createCollections(MongoClient mongoClient,String dbName,String...collections){ if(null == mongoClient) return PLEASE_INSTANCE_MONGOCLIENT; if(null==collections || collections.length==0){ return CREATE_MONGO_COLLECTION_NOTE; } MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName); if(null == mongoDatabase) return NO_THIS_MONGO_DATABASE; try { 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); }catch (Exception e){ e.printStackTrace(); logger.error(CREATE_MONGO_COLLECTION_EXCEPTION); } return null; } /** * 获取MongoCollection * @param mongoClient * @param dbName * @param collection * @return */ public MongoCollection<Document> getMongoCollection(MongoClient mongoClient,String dbName,String collection){ if(null == mongoClient) return null; if(StringUtils.isBlank(dbName)) return null; if(StringUtils.isBlank(collection)) return null; MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName); MongoCollection<Document> collectionDocuments = mongoDatabase.getCollection(collection); if(null == collectionDocuments) return null; return collectionDocuments; } /** * 获取到MongoClient * @param ip * @param port * @param userName * @param dbName * @param psw * @returnMongoClient */ public static MongoClient getMongoClientByCredential(String ip,int port,String userName,String dbName,String psw){ ServerAddress serverAddress = new 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 = new MongoClient(addrs,credentials); return mongoClient; } /** * 插入文档数据 * @param mongoCollection * @param params */ public void insertDoucument(final MongoCollection<Document> mongoCollection, final Map<String,Object> params){ if(null == mongoCollection) { logger.info(NO_FOUND_MONGO_COLLECTION); return; } try { Document document = new 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); }catch (Exception e){ e.printStackTrace(); logger.error(INSERT_DOCUMEN_EXCEPTION); } } /** * 更新文档 * @param mongoCollection * @param conditionParams * @param updateParams */ public void updateDocument(final MongoCollection<Document> mongoCollection,final Map<String,Object> conditionParams, final Map<String,Object> updateParams,final boolean MultiUpdate ){ if(null == mongoCollection) return; if (null == conditionParams) return; if (null == updateParams) return; Document conditonDocument = new Document(); conditionParams.keySet().stream().filter(p -> null != p).forEach(o -> { conditonDocument.append(o,conditionParams.get(o)); }); Document updateDocument = new Document(); updateParams.keySet().stream().filter(p -> null != p).forEach(o -> { updateDocument.append(o,updateParams.get(o)); }); UpdateResult updateResult = null; if (MultiUpdate){//是否批量更新 updateResult = mongoCollection.updateMany(conditonDocument,new Document("$set",updateDocument)); }else { updateResult = mongoCollection.updateOne(conditonDocument,new Document("$set",updateDocument)); } System.out.println("修改了:"+updateResult.getModifiedCount()+" 条数据 "); } /** *条件 删除文档 是否多条删除 * @param mongoCollection * @param multiple * @param conditionParams * @return */ public long deleteDocument(final MongoCollection<Document> mongoCollection,final boolean multiple, final Map<String,Object> conditionParams){ if(null == mongoCollection) return 0; if(null == conditionParams) return 0; Document document = new Document(); conditionParams.keySet().stream().filter(p -> null != p).forEach(o -> { document.append(o,conditionParams.get(o)); }); if(multiple) { return mongoCollection.deleteMany(document).getDeletedCount(); } //删除文档第一条 return mongoCollection.deleteOne(document).getDeletedCount(); } /** * 查询文档 带条件、范围查找、排序、分页 * @param mongoCollection * @param conditionParams * @param limit * @param skip * @param sortParams */ public FindIterable<Document> queryDocument(final MongoCollection<Document> mongoCollection, final Map<String,Object> conditionParams, final String op,final String compareField, final Map<String,Integer> gtLtOrOtherParams, final Map<String,Object> sortParams,final Integer skip,final Integer limit ){ if(null == mongoCollection) return null; FindIterable<Document> findIterable = mongoCollection.find(); Document conditionDocument = new Document(); Document compareDocument = new Document(); if(null != conditionParams && null != findIterable){ conditionParams.forEach((k,v) ->{ if (StringUtils.isNotBlank(k)) { conditionDocument.append(k,v); } }); findIterable = findIterable.filter(conditionDocument); MongoCursor<Document> mongoCursor = findIterable.iterator(); while(mongoCursor.hasNext()){ System.out.println("条件过滤 -->"+mongoCursor.next()); } } if(null != findIterable && null != gtLtOrOtherParams){ Document gtOrLtDoc = new Document(); gtLtOrOtherParams.forEach((k,v) -> { if(StringUtils.isNotBlank(k)) gtOrLtDoc.append(k,v); }); compareDocument = new Document(compareField,gtOrLtDoc); findIterable = findIterable.filter(new Document(compareField,compareDocument)); } if (StringUtils.isNotBlank(op)){ if ("and".equals(op)){ findIterable = mongoCollection.find(Filters.and(conditionDocument,compareDocument)); }else if("or".equals(op)){ findIterable = mongoCollection.find(Filters.or(conditionDocument,compareDocument)); }else if("not".equals(op)){//排除范围 findIterable = mongoCollection.find(Filters.and(conditionDocument,Filters.not(compareDocument))); } }else{//默认是AND查询 findIterable = mongoCollection.find(Filters.and(conditionDocument,compareDocument)); } MongoCursor<Document> mongoCursor3 = findIterable.iterator(); while(mongoCursor3.hasNext()){ System.out.println(op+"过滤 -->"+mongoCursor3.next()); } if(null != sortParams){ Document sortDocument = new Document(); sortParams.forEach((k,v) ->{ if (StringUtils.isNotBlank(k)) { sortDocument.append(k,v); } }); findIterable = findIterable.sort(sortDocument); MongoCursor<Document> mongoCursor2 = findIterable.iterator(); while(mongoCursor2.hasNext()){ System.out.println("排序 -->"+mongoCursor2.next()); } } if(null != findIterable && null != limit){ findIterable = findIterable.limit(limit); } if(null != findIterable && null != skip){ findIterable = findIterable.skip(skip); } return findIterable; } /** * in查询 * @param mongoCollection * @return */ public FindIterable<Document> queryDocumentIn(final MongoCollection<Document> mongoCollection,String field, List<String> list ){ if(null == mongoCollection) return null; FindIterable<Document> findIterable = mongoCollection.find(new Document(field,new Document("$in",list))); return findIterable; } /** * 全文查询 * @param mongoCollection * @return */ public FindIterable<Document> queryDocument(final MongoCollection<Document> mongoCollection ){ if(null == mongoCollection) return null; FindIterable<Document> findIterable = mongoCollection.find(); return findIterable; } /** * 查询文档 简单条件查询 * @param mongoCollection * @param conditionParams * @return */ public FindIterable<Document> queryDocument(final MongoCollection<Document> mongoCollection, final Map<String,Object> conditionParams ){ if(null == mongoCollection) return null; FindIterable<Document> findIterable = mongoCollection.find(); if(null == conditionParams || null == findIterable) return findIterable; Document document = new Document(); conditionParams.forEach((k,v)->{ if (StringUtils.isNotBlank(k)) { document.append(k,v); } }); findIterable = findIterable.filter(document); return findIterable; } /** * 用于输出部分的列信息 * @param documents */ public static void printDocuments(FindIterable<Document> documents, String[] fields) { if (fields != null && fields.length > 0) { int num = 0; for (Document d : documents) { StringBuilder stringBuilder = new StringBuilder(); for (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); } }else{ for (Document d : documents) { System.out.println(d.toString()); } } } /** * 用于输出所有的列信息 * @param documents */ public void printDocuments(FindIterable<Document> documents) { int num = 0; for (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/
微信:17873041739