import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.UpdateManyModel;
import com.mongodb.client.model.geojson.Point;
import com.mongodb.client.model.geojson.Polygon;
import com.mongodb.client.model.geojson.Position;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* 原生java操作MongoDB工具类
*
* @author: lanweixing
* @create: 2019-05-15 14:06
**/
@Component
public class MongodbManageHandler {
private final static Logger logger = LoggerFactory.getLogger(MongodbManageHandler.class);
@Value("${r.mongo.dbname}")
private String dbName ;
@Autowired
private MongoClient mongodbClient;
/**
* 获取Mongodb集合
*
* @param collectionName
* @return
*/
public MongoCollection doGetMongoCollection(String collectionName){
MongoDatabase database = this.mongodbClient.getDatabase(this.dbName);
if(database != null){
return database.getCollection(collectionName);
}
return null ;
}
/**
* 通过经纬度获取区域ID
* 一个经纬度只能在一个区域内
*
*
* @param lng
* @param lat
* @return
*/
public List<Long> doGetAreaIdByLngAndLat(Double lng, Double lat){
Preconditions.checkNotNull(lng,"经度不能为空");
Preconditions.checkNotNull(lat,"纬度不能为空");
Preconditions.checkState(lng != 0,"经度不能为0");
Preconditions.checkState(lat != 0,"纬度不能为0");
Stopwatch stopwatch = Stopwatch.createStarted();
List<Long> areaIds = Lists.newArrayList();
try{
MongoCollection mongoCollection = this.doGetMongoCollection("cityServiceArea");
if(mongoCollection != null){
FindIterable findIterable = mongoCollection.find(Filters.geoIntersects("geo",new Point(new Position(lng,lat))));
if(findIterable != null){
Document document = (Document)findIterable.first();
if(document != null){
areaIds.add((long)document.get("_id"));
}
}
}
logger.info("【SBS】通过经纬度获取区域值ID:{} 耗时:{}", JSON.toJSONString(areaIds),stopwatch.stop());
return areaIds;
}catch (Exception e){
logger.info("【SBS】通过经纬度获取区域ID出错,{}",e);
throw new BusinessException(ErrorCodeConstants.BUSINESS_ERROR, "通过经纬度获取区域异常");
}
}
/**
* 批量插入区域信息
*
* @param cityServiceAreas
*/
public void doBatchInsertCityServiceArea(List<CityServiceArea> cityServiceAreas){
Stopwatch stopwatch = Stopwatch.createStarted();
if(CollectionUtils.isNotEmpty(cityServiceAreas)){
MongoCollection mongoCollection = this.doGetMongoCollection("cityServiceArea");
if(mongoCollection != null){
try {
List<Document> saveCollections = Lists.newArrayList();
for(CityServiceArea cityServiceArea : cityServiceAreas){
if(cityServiceArea != null){
Document document = new Document();
document.append("_id", cityServiceArea.getId());
document.append("_class","com.hk.sbs.mongodb.CityServiceAreaMongo");
if(StringUtils.isNotEmpty(cityServiceArea.getServiceArea())){
document.append("geo",new Polygon(Arrays.stream(cityServiceArea.getServiceArea().split("@")).map(lonLats -> lonLats.split(",")).map(lonLat -> new Position(Double.parseDouble(lonLat[0]), Double.parseDouble(lonLat[1]))).collect(Collectors.toList())));
}
document.append("cityCode",cityServiceArea.getCityCode());
document.append("cityName",cityServiceArea.getCityName());
saveCollections.add(document);
}
}
mongoCollection.insertMany(saveCollections);
logger.info("【SBS】批量保存区域数据耗时:{}",stopwatch.stop());
} catch (Exception e) {
logger.info("【SBS】批量保存区域数据异常,{}",e);
throw new BusinessException(ErrorCodeConstants.BUSINESS_ERROR, "批量保存区域数据异常");
}
}
}
}
/**
* 批量更新区域信息
*
* @param cityServiceAreas
*/
public void doBatchUpdateCityServiceArea(List<CityServiceArea> cityServiceAreas){
Stopwatch stopwatch = Stopwatch.createStarted();
if(CollectionUtils.isNotEmpty(cityServiceAreas)){
MongoCollection mongoCollection = this.doGetMongoCollection("cityServiceArea");
if(mongoCollection != null){
try {
List<UpdateManyModel<Document>> updateCollections = Lists.newArrayList();
for(CityServiceArea cityServiceArea : cityServiceAreas){
if(cityServiceArea != null){
Document queryDocument = new Document("_id", cityServiceArea.getId());
Document setDocument = new Document()
.append("_class","com.hk.sbs.mongodb.CityServiceAreaMongo");
if(StringUtils.isNotEmpty(cityServiceArea.getServiceArea())){
setDocument.append("geo",new Polygon(Arrays.stream(cityServiceArea.getServiceArea().split("@")).map(lonLats -> lonLats.split(",")).map(lonLat -> new Position(Double.parseDouble(lonLat[0]), Double.parseDouble(lonLat[1]))).collect(Collectors.toList())));
}
setDocument.append("cityCode",cityServiceArea.getCityCode());
setDocument.append("cityName",cityServiceArea.getCityName());
updateCollections.add(new UpdateManyModel<Document>(queryDocument,new Document("$set",setDocument)));
}
}
mongoCollection.bulkWrite(updateCollections);
logger.info("【SBS】批量更新区域数据耗时:{}",stopwatch.stop());
} catch (Exception e) {
logger.info("【SBS】批量更新区域数据异常,{}",e);
throw new BusinessException(ErrorCodeConstants.BUSINESS_ERROR, "批量更新区域数据异常");
}
}
}
}
}
分享到:
相关推荐
MongoDB原生高可用及分布式能力解析.pdf
MongoDB原生高可用及分布式能力解析.pptx
MongoDB操作类源码包括添加、修改、删除和查询(包括分页)等同步及异步操作类完整的代码。 本项目是以最新版的MVC结合MongoDB呈现,对MongoDB有兴趣的朋友很有参考价值。 可以直接拿到自己的项目直接开发,可以少走...
php Mongodb操作类,可以实现CURD等操作
介绍了PHP实现的MongoDB数据库操作类分享,模板mysql版的操作类,支持传入多个mongo_server(1.一个出问题时连接其它的server 2.自动将查询均匀分发到不同server),创建索引:如索引已存在,则返回。
引用MongoDB.Driver,MongoDB.Bson,链接MongoDB数据库,操作增删改查和索引操作
本demo适用于初学mongodb操作集合,文件使用
将mongodb的基本操作,增删查询等封装为一个基本类供人调用
PHP实现的MongoDB数据库操作类分享,模板mysql版的操作类,支持传入多个mongo_server(1.一个出问题时连接其它的server 2.自动将查询均匀分发到不同server),创建索引:如索引已存在,则返回。
分享一个php封装的mongodb操作类,有需要的朋友们可以下载参考。
官方的Mongo DB原生NodeJS驱动器
一个基于Node和原生MongoDB的微博系统
C#MongoDb操作工具类,具体怎么操作,请看的文章: http://blog.csdn.net/lablenet/article/details/47257951
java操作mongodb的工具类,增删查改方法
最近的项目开发中使用的数据库是mongodb数据库,因为小编的公司也是刚刚使用mongodb数据库,所以之前没有封装好的mongodb数据库操作类拿来使用,所以小编在项目中自己封装了一个mongodb数据库操作类,特拿出来分享,...
WpfMongoDbCsharp 根据网上提供的封装类做了简单的测试程序 代码有插入的例子 其他自己参考 mongodb driver是2.7.0稳定版
在别人基础上修改的mongodb操作类,适合mongodb2.x和mongodb3.x <?php /*** Mongodb类** examples: * $mongo = new HMongodb("127.0.0.1:11223"); * $mongo->selectDb("test_db"); * 创建索引 * $mongo->...
php7简单链接mongodb类
主要介绍了PHP实现的MongoDB数据库操作类分享,模板mysql版的操作类,需要的朋友可以参考下
一、MongoDB简介 二、Windows下MongoDB操作