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

MongoDB系列:C#、Java驱动连接MongoDB以及封装(C#的MongoDBHelper,Java的MongoDBUtil)的更多相关文章

  1. MongoDB学习-->命令行增删改查&JAVA驱动操作Mongodb

    MongoDB 是一个基于分布式文件存储的数据库. 由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关 ...

  2. MongoDB聚合查询及Python连接MongoDB操作

    今日内容概要 聚合查询 Python操作MongoDB 第三方可视化视图工具 今日内容详细 聚合查询 Python操作MongoDB 数据准备 from pymongo import MongoCli ...

  3. 左手Mongodb右手Redis 通过python连接mongodb

    首先需要安装第三方包pymongo pip install pymongodb """ 通过python连接mongodb数据库 首先需要初始化数据库连接 "& ...

  4. mongodb系列3 mongo mongoskin 连接以及连接数的问题进阶

    1)使用mongodb连接mongo var mongo = require('mongodb'), //引入mongodb dbHost = '127.0.0.1', dbPort = 27017; ...

  5. MongoDB 系列(一) C# 类似EF语法简单封装

    之前写过一篇关于MongoDB的封装 发现太过繁琐 于是打算从新写一篇简易版 1:关于MongoDB的安装请自行百度,进行权限认证的时候有一个小坑,3.0之后授权认证方式默认的SCRAM-SHA-1模 ...

  6. ubuntu18.04 安装mongodb并使用Robo 3T连接Mongodb数据库

    1.前提: 系统:ubuntu18.04  64位 数据库:mongodb GUI:Robo 3T  2018.3.0 描述: mongodb 安装在局域网内的ubuntu的机子上面,  在win 下 ...

  7. mongodb系列~关于双活状态的mongodb集群

    一简介:说说我们异地双活的集群 二 背景:需要建立异地双活的架构 三 构建 1 需要保证第二机房至少两个副本集DB,这样在第一机房挂掉后才能保证第二机房的可用性 2 集群状态下第二机房启用config ...

  8. 启动mongodb报错,无法连接mongodb

    报错原因如下: MongoDB shell version v3.4.2 connecting to: mongodb://127.0.0.1:27017 --01T12:: W NETWORK [t ...

  9. (最详细)JAVA如何连接虚拟机的HBASE和hadoop(JAVA如何远程访问虚拟机HBASE)

    第一步: 首先把虚拟机和你的主机(本地电脑)弄通这样本地机器才能访问虚拟机里面的内容 我用的虚拟机为 VMware Workstation linux 为 centeros 补充一点虚拟机设置 1  ...

  10. MongoDB的Java驱动使用整理 (转)

    MongoDB Java Driver 简单操作 一.Java驱动一致性 MongoDB的Java驱动是线程安全的,对于一般的应用,只要一个Mongo实例即可,Mongo有个内置的连接池(池大小默认为 ...

随机推荐

  1. Writing your first Django app, part 1

    Let's learn by example. Throughout this tutorial, we'll walk you through the creation of a basic pol ...

  2. MySQL的驱动表与被驱动表

    驱动表与被驱动表的含义 在MySQL中进行多表联合查询时,MySQL会通过驱动表的结果集作为基础数据,在被驱动表中匹配对应的数据,匹配成功合并后的临时表再作为驱动表或被驱动表继续与第三张表进行匹配合并 ...

  3. Windows下音视频对讲演示程序(声学回音消除、噪音抑制、语音活动检测、自动增益控制、自适应抖动缓冲)(2023年07月13日更新)

    Windows下音视频对讲演示程序 必读说明 简介   本软件根据<道德经>为核心思想而设计,实现了两个设备之间进行音视频对讲,一般可用于楼宇对讲.智能门铃对讲.企业员工对讲.智能对讲机. ...

  4. 记一次服务器Cuda驱动崩溃修复过程

    基本过程 今天实验室师兄在服务器运行深度学习训练时候得到报错CUDA initialization: Unexpected error from cudaGetDeviceCount()疑似Cuda与 ...

  5. Windows虚拟机环境下Linux设置固定IP地址

    Linux 设置固定IP地址 安装环境是VMware Workstation Pro 15 安装完linux之后需要做的第一件事就是配置网络,有了网络我们可以下载插件,使用xshell工具连接等等 i ...

  6. Redis7新特性简介及十大数据类型

    Redis是基于内存的K-V键值对内存数据库 浅谈Redis7新特性 主要是自身底层性能和资源利用率上的提高和优化. 多AOF文件支持 config命令增强 限制客户端内存使用 listpack紧凑列 ...

  7. Xmind思维导图工具2023最新专业版破解思路

    工具介绍 XMind 是一款最为流行的专业级思维_导图_制作与编辑软件,它现在在全球范围内都已极具名气,可谓是办公.学习.团队交流必备工具之一. 准备工作 1,官方Xmind软件 2,一个心意的编辑器 ...

  8. OpenAI宫斗反转反转再反转,到底是资本任性还是人性扭曲?

    最近OpenAI发生了一件大事,创始人山姆·奥特曼被董事会开除了,这在AI界引起了轩然大波. 事件经过 我们先来捋一下事件经过,时间以美国旧金山当地时间为准. 11月17日 11月17日12点(北京时 ...

  9. Kubernetes 漫游:kube-scheduler

    概述 什么是 kube-scheduler ? Kubernetes 集群的核心组件之一,它负责为新创建的 Pods 分配节点.它根据多种因素进行决策,包括: 资源需求和限制:考虑每个 Pod 请求的 ...

  10. 【Codeforces Global Round 12】 C2 - Errich-Tac-Toe题解(思维)

    题面 题目要求不能有有三个连续相同的'X'或'O',注意到这样的连续串它们的横纵坐标之和是连续变化的,考虑将它们按照横纵坐标之和对 \(3\)的模值分组,因为这样分组后相邻的三个相同字符就被分到了三个 ...