首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

mongodb数据库使用方法

记录一下使用过的mongodb的一些增删改查

1 --------------MongoDBDS------

0package sunline.common.logic.mongodb;

import java.util.Arrays;

import java.util.Map;

import org.apache.log4j.Logger;

import org.bson.BSONObject;

import cn.sunline.ltts.base.ftp.exception.DBConnectionException;

import cn.sunline.ltts.base.ftp.fs.MongoDBConnection;

import com.mongodb.BasicDBList;

import com.mongodb.BasicDBObject;

import com.mongodb.DB;

import com.mongodb.DBCollection;

import com.mongodb.DBCursor;

import com.mongodb.DBObject;

public class MongoDBDS {

private final static Logger logger = Logger.getLogger(MongoDBDS.class);

private DBCollection collection;

private String bucketName;

public MongoDBDS(String bucketName) {

this.bucketName = bucketName;

try {

DB db = MongoDBConnection.getInstance().getDB();

collection = db.getCollection(this.bucketName + "");

} catch (DBConnectionException ex) {

logger.error(ex.getMessage(), ex);

}

}

public void add(DBObject obj) {

collection.save(obj);

}

public void query() {

DBCursor cursor = collection.find();

System.out.println(cursor.count());

while (cursor.hasNext()) {

System.out.println(cursor.next());

}

}

public DBObject find(BasicDBObject condition, String str) {

DBCursor find = collection.find(condition);

//BSONObject cursor = null;

DBObject cursor = null;

while (find.hasNext()) {

cursor=find.next();

}

return cursor;

}

//查询数据并返回

/* public DBObject queryData(String str) {

BasicDBObject query = new BasicDBObject();

query.put("serialNo", new BasicDBObject("$eq", str));

return find(query, "(查询mongodb是否已有记录),流水号:"+str);

}*/

//查询数据并返回

public DBObject queryData(String str,String ecno) {

BasicDBObject query = new BasicDBObject();

BasicDBObject seqObj = new BasicDBObject("serialNo",new BasicDBObject("$eq", str));

BasicDBObject ecnoObj = new BasicDBObject("externalEcno",new BasicDBObject("$eq", ecno));

BasicDBObject andObj = new BasicDBObject("$and",Arrays.asList(seqObj,ecnoObj));

return find(andObj, "(查询mongodb是否已有记录),流水号:"+str+",商户号:"+ ecno);

}

// 删除数据

public void remove() {

DBObject query = new BasicDBObject();

query.put("age", new BasicDBObject("$eq", 123));

collection.remove(query);

}

// 局部更新,只更改某些列

public void update(Map data,String str,String ecno) {

// update(query,set,false,true);

// query:需要修改的数据查询条件,相当于关系型数据库where后的语句

// set:需要设的值,相当于关系型数据库的set语句

// false:需要修改的数据如果不存在,是否插入新数据,false不插入,true插入

// true:如果查询出多条则不进行修改,false:只修改第一条

BasicDBObject seqObj = new BasicDBObject("serialNo",new BasicDBObject("$eq", str));

BasicDBObject ecnoObj = new BasicDBObject("externalEcno",new BasicDBObject("$eq", ecno));

BasicDBObject andObj = new BasicDBObject("$and",Arrays.asList(seqObj,ecnoObj));

// 加上$set会是局部更新,不会丢掉某些列

BasicDBObject set = new BasicDBObject("$set", new BasicDBObject("res", data.get("res")).append("resTime", data.get("resTime")).append("bizSeqNo", data.get("bizSeqNo")).append("resSign", data.get("resSign")).append("resEncrypt", data.get("resEncrypt")));

collection.update(andObj, // 需要修改的数据条件

set,// 需要赋的值

false,// 数据如果不存在,是否新建

false);// false只修改第一条,true如果有多条就不修改

}

//yangweijie

public void updateORinsert(Map data,String orderNo,Boolean flag) {

// update(query,set,false,true);

// query:需要修改的数据查询条件,相当于关系型数据库where后的语句

// set:需要设的值,相当于关系型数据库的set语句

// false:需要修改的数据如果不存在,是否插入新数据,false不插入,true插入

// true:如果查询出多条则不进行修改,false:只修改第一条

//先进行查询

BasicDBObject orderObj = new BasicDBObject("orderNo",new BasicDBObject("$eq", orderNo));

//进行赋值

DBObject obj = new BasicDBObject();

for (Map.Entry entry : data.entrySet()) {

obj.put(entry.getKey(), entry.getValue());

}

collection.update(orderObj, // 需要修改的数据条件

obj,// 需要赋的值

flag,// 数据如果不存在,是否新建(设定不存在新建,传true)

false);// false只修改第一条,true如果有多条就不修改

}

//yangweijie 根据条件查询

public DBObject querys(Map data,String arg1){

BasicDBList condList = new BasicDBList();

BasicDBObject query = new BasicDBObject();

query.append(arg1,new BasicDBObject("$eq",data.get(arg1)));

//query.append(arg2,new BasicDBObject("$eq",data.get(arg2)));

condList.add(query);

BasicDBObject search= new BasicDBObject();

search.put("$and", condList);

//然后查询数据:

DBObject find = find(search, "(查询mongodb是否已有记录)参数1:"+arg1);

return find;

}

}

--------2----------MongoDBDao------

package sunline.common.logic.mongodb;

import java.io.File;

import java.net.UnknownHostException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.bson.BSONObject;

import cn.sunline.ltts.base.ftp.Uploader;

import cn.sunline.ltts.base.ftp.exception.DBConnectionException;

import cn.sunline.ltts.base.ftp.fs.MongoDBConnection;

import cn.sunline.ltts.base.ftp.utils.FileType;

import cn.sunline.ltts.base.ftp.utils.SysType;

import com.mongodb.BasicDBObject;

import com.mongodb.DBCursor;

import com.mongodb.DBObject;

import com.mongodb.ServerAddress;

import com.sunline.flow.base.Settings;

import com.sunline.flow.base.annotation.Bizlet;

import com.sunline.flow.base.util.StringUtils;

public class MongoDBDao {

private static final Log LOG = LogFactory.getLog(MongoDBDao.class);

static {

try {

List serverAddrs = new ArrayList();

String dburl = Settings.getString("mongodb.url", "");

String url[] = dburl.split(",");

for (int i = 0; i

String iport[] = url[i].split(":");

serverAddrs.add(new ServerAddress(iport[0], Integer.valueOf(iport[1])));

}

String user = Settings.getString("mongodb.username", "");

String password = Settings.getString("mongodb.password", "");

if (StringUtils.isBlank(user) || StringUtils.isBlank(password)) {

// 如果用户名或密码为空,则表示服务端无校验,客户端不需要使用用户名和密码校验

MongoDBConnection.getInstance().connect(serverAddrs);

} else {

MongoDBConnection.getInstance().connect(serverAddrs, user, password);

}

} catch (UnknownHostException e) {

LOG.error(e);

} catch (DBConnectionException e) {

LOG.error(e);

}

}

@Bizlet(value = "openAPI登记报文到mongodb")

/**

*

*/

public static void addLog(Map data) {

MongoDBDS ds = DSFactory.getInstance().create("phfund_openApi_log");

DBObject obj = new BasicDBObject();

for (Map.Entry entry : data.entrySet()) {

obj.put(entry.getKey(), entry.getValue());

}

ds.add(obj);

}

public static void queryLog() {

MongoDBDS create = DSFactory.getInstance().create("phfund_openApi_log");

create.query();

}

@Bizlet(value = "openAPI更新报文到mongodb")

/**

*

*/

public static void updateLog(Map data,String str,String ecno) {

LOG.info(">>>>>>>>>更新报文登记的商户编号:"+ecno+",业务请求流水号:"+str);

MongoDBDS create = DSFactory.getInstance().create("phfund_openApi_log");

create.update(data, str,ecno);

}

@Bizlet(value = "openAPI查询mngodb中是否已有记录")

public static DBObject query(String str,String ecno) {

MongoDBDS create = DSFactory.getInstance().create("phfund_openApi_log");

return create.queryData(str,ecno);

}

@Bizlet(value = "openAPI查询mngodb中是否已有记录(条件查询)")

public static DBObject querys(Map data,String arg1) {

MongoDBDS create = DSFactory.getInstance().create("phfund_openApi_log");

return create.querys(data,arg1);

}

public static void removeLog() {

MongoDBDS create = DSFactory.getInstance().create("phfund_openApi_log");

create.remove();

}

/**

* yangweijie

*/

@Bizlet(value = "openAPI上传mngodb文件")

public static String fileUpload(String pathName) {

File file=new File(pathName);

Uploader up = new Uploader(file, SysType.BFF, FileType.day);

up.upload();

return up.getFilename();

}

/**

*

* @param data

* @param arg1 查询条件参数1 为data中参数

* @param arg2 需要提取的参数 如取出状态值返回.

*/

@Bizlet(value = "mngodb返回的值中取出特定的值")

public static String queryone(Map data,String arg1,String arg2){

DBObject querys = querys(data,arg1);

if(querys==null){

return "";

}

String string = getString(querys, arg2);

return string;

}

/**

* yangweijie 获取某个参数的方法

*/

@Bizlet(value = "mngodb返回的值中取出特定的值")

public static String getString(DBObject obj,String arg){

if(obj.get(arg)!=null&&!"".equals(obj.get(arg))){

return obj.get(arg).toString();

}

return "";

}

/**

* yangweijie

* @param data

*/

@Bizlet(value = "openAPI新增或者更新mongodb")

public static void InsertOrupdate(Map data,String orderNo,Boolean flag) {

LOG.info(">>>>>>>>>新增或者更新记录");

MongoDBDS create = DSFactory.getInstance().create("phfund_openApi_log");

create.updateORinsert(data, orderNo,flag);

}

public static void main(String[] args) {

Map map = new HashMap();

map.put("orderNo", "12345678Oo1");

map.put("fileName", "12345678Oo1.zip");

map.put("status", "1");

DBObject cursor= querys(map, "orderNo");

cursor.get("fileName");

System.out.println("1"+cursor.get("fileName"));

//InsertOrupdate(map, "12345678Oo1", true);

//MongoDBDao.addLog(map);

// MongoDBDao.queryLog();

// System.out.println(map);

//MongoDBDao.removeLog();

}

}

-----3----------------DSFactory------------

package sunline.common.logic.mongodb;

import java.util.concurrent.ConcurrentHashMap;

import java.util.concurrent.ConcurrentMap;

public class DSFactory {

private final ConcurrentMap cache = new ConcurrentHashMap();

private static class Holder {

final static DSFactory instance = new DSFactory();

}

/**

* 懒汉式单例,延迟加载

*

* @return

*/

public static DSFactory getInstance() {

return Holder.instance;

}

public MongoDBDS create(String bucketName) {

MongoDBDS ds = cache.get(bucketName);

if (ds == null) {

synchronized (cache) {

if (ds == null) {

ds = new MongoDBDS(bucketName);

MongoDBDS temp = cache.putIfAbsent(bucketName, ds);

if (temp != null) {

ds = temp;

}

}

}

}

return ds;

}

}

----------设计到的方法就是以上的---------

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20180901G1H3WK00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券