package com.martin.test;/*
* @Author Martin·Antonio
* @Description TODO
* @DateTime 2021/6/15 16:08
* */
import com.mongodb.BasicDBObject;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class MongoApi {
//1操作集合对象
MongoCollection<Document> userTable = null;
//2客户端对象
MongoClient client = null;
@Before
public void init(){
//3建立连接
client = MongoClients.create("mongodb://192.168.67.138:27017");
//4连接数据库
MongoDatabase database = client.getDatabase("demo");
//5获取要操作的集合
userTable = database.getCollection("user");
}
@After
public void close(){
client.close();
}
@Test
public void testQuery(){
//查询所有
FindIterable<Document> documents = userTable.find();
for (Document document : documents){
System.out.println(document);
}
}
@Test
public void testQuerywithCodetion(){
//按条件查询
Bson filter = Filters.gt("age",20);//gt=greater than,gte=greater than equal,lt=less than ,lte同上
FindIterable<Document> documents = userTable.find(filter);
for (Document document : documents){
System.out.println(document);
}
}
@Test
public void testPage(){
//按条件进行分页
FindIterable<Document> documents = userTable.find().skip(2).limit(2);
for (Document document:documents){
System.out.println(document);
}
}
//更新
@Test
public void testupdate(){
userTable.updateOne(Filters.eq("_id",1), Updates.set("age",40));
}
//删除
@Test
public void testDelete(){
userTable.deleteMany(new BasicDBObject());
}
}
Idea中对MongoDB的简单增删查改
最新推荐文章于 2024-09-19 09:10:38 发布
该博客介绍了如何使用Java MongoDB API进行数据库操作,包括连接MongoDB服务器、查询、条件过滤、分页以及更新和删除数据。示例代码详细展示了MongoClient、MongoDatabase和MongoCollection的使用方法。
摘要由CSDN通过智能技术生成