mongodb的java操作

需要先导入mongodb的jar包

这里只给出关键的代码

首先需要给出ip 端口号 和数据库名称

private static final String ip = "192.168.10.8"; // ip地址
private static final int port = 27017; // 端口
private static final String dataBaseName = "ice";


然后去创建mongodbClient

	public static MongoClient getMongoClient() {
		MongoClient mongoClient = new MongoClient(ip, port);
		return mongoClient;
	}

通过mongoClient来获取数据库

	public static MongoDatabase getDatabase(MongoClient mongoClient, String databaseName) {
		MongoDatabase database = mongoClient.getDatabase(databaseName);
		return database;
	}
以后通过数据库名称来获取一个集合,接下来的增删改查都需要mongoCollection来操作,当需要去创建一个集合的时候,可以使用 database .createCollection( collectionName );

public static MongoCollection<Document> getCollection(MongoDatabase database, String collectionName)
			throws Exception {
		MongoCollection<Document> collection = null;
		if (database != null) {
			collection = database.getCollection(collectionName);
		} else {
			throw new Exception("数据库还没有链接,请链接数据库");
		}
		return collection;
	}

接下来的增删改查的操作
mongodb的一条数据是一组文本,在其中用Document,
使用
mongoCollection.insertOne(document);               //插入单条数据
mongoCollection.insertMany(documents);          //插入多条数据(mongodb没有事务)

删除
mongoCollection.deleteOne(new Documnet("key","value"));  new Document(key,value);删除key=value的一条数据,
mongoCollection.deleteOne(Filter.eq(key,value));   Filter.eq(key,value); 条件过滤,这样就删除了一条key=value的数据
mongoCollection.deleteMany(Filter.eq(key,value));          删除多条数据

查询
mongoCollection.find();查询所有的数据
mongoCollection.find(new Document());     //查询有这个条件的数据
返回一个数据

根据条件查询

public static List<String> getDocumentByCondition(MongoCollection<Document> collection, Document document) {
		List<String> list = new ArrayList<String>();
		FindIterable<Document> findIterable = null;
		if (document != null && !document.isEmpty()) {
			findIterable = collection.find(document);
		}else{
			findIterable = collection.find();
		}
		MongoCursor<Document> cursor = findIterable.iterator();
		try {
			while (cursor.hasNext()) {
				String json = cursor.next().toJson();
				list.add(json);
			}
		} finally {
			cursor.close();
		}
		return list;
	}

可以查询一条数据
mongoCollection.find().first().toJson();                //查询一条数据,这条数据变成为一条json格式字符串
更新语句
/**
     * 更新,通过_id进行更新
     *
     * @param collection
     * @param key        查询条件(该条件为_id,mongodb自动生成的主键)
     * @param setFields  更新对象
     */
    public void updateById(String collection, String key, String value, Document setFields) {
        getCollection(collection).updateMany(Filters.eq(key, new ObjectId(value)), new Document("$set", new Document(setFields)));
    }
    /**
     * 更新,通过除开_id的条件进行更新
     *
     * @param collection
     * @param key        查询条件
     * @param setFields  更新对象
     */
    public void updateByCondition(String collection, String key, String value, Document setFields) {
        getCollection(collection).updateMany(Filters.eq(key, value), new Document("$set", new Document(setFields)));
    }


分页查询数据

/**
     * 分页查找集合对象,返回特定字段
     *
     * @param collection
     * @param document   查询条件
     * @param pageNo     返回字段 , Document fileds
     * @pageNo 第n页
     * @perPageCount 每页记录数
     */
    public FindIterable<Document> findLess(String collection, Document document, int pageNo,
                                           int perPageCount) {
        return getCollection(collection).find(document).skip((pageNo - 1) * perPageCount).limit(perPageCount);
    }
/**
     * 按顺序分页查找集合对象,返回特定字段
     *
     * @param collection   集合
     * @param document     查询条件
     * @param fileds       返回字段
     * @param orderBy      排序
     * @param pageNo       第n页
     * @param perPageCount 每页记录数
     */
    public FindIterable<Document> findLess(String collection, Document document, String fileds, Document orderBy,
                                           int pageNo, int perPageCount) {
        return getCollection(collection).find(document).projection(fields(include(fileds)))
                .sort(orderBy).skip((pageNo - 1) * perPageCount).limit(perPageCount);
    }


当mongodb数据库需要用户名和密码的时候,及在启动mongodb是启动了权限认证,那么这里就需要多写一点东西,如下:

ServerAddress serverAddress = new ServerAddress("localhost",27017);  
            List<ServerAddress> addrs = new ArrayList<ServerAddress>();  
            addrs.add(serverAddress);  
              
            //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码  
            MongoCredential credential = MongoCredential.createScramSha1Credential
("username", "databaseName", "password".toCharArray());  
            List<MongoCredential> credentials = new ArrayList<MongoCredential>();  
            credentials.add(credential);  
            //通过连接认证获取MongoDB连接  
            MongoClient mongoClient = new MongoClient(addrs,credentials);  
              
            //连接到数据库  
            MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");  











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值