您的位置:首页 > 数据库 > Mongodb

MongoDB的Java操作

2016-09-23 17:02 337 查看
// 需要三个jar包,mongodb-driver-3.3.0.jar;mongodb-drvier-core-3.3.0.jar;bson-3.3.0.jar
public class MongoTest {
private MongoClient conn = null;

// 获取连接
private MongoClient getConn() {
conn = new MongoClient("127.0.0.1", 27017);
return conn;
}

// 关闭连接
private void close(MongoClient conn) {
conn.close();
}

public void insert() {
conn = this.getConn();
// 获取test数据库,没有自动创建
MongoDatabase db = conn.getDatabase("test");
// 获取ss集合,没有自动创建
MongoCollection<Document> collection = db.getCollection("ss");

// 创建文档
Document doc = new Document("name", "lt").append("sex", "男").append("age", 30);
// 单量插入
collection.insertOne(doc);
// 批量插入
List<Document> docList = new ArrayList<Document>();
for (int i = 0; i < 20; i++) {
docList.add(new Document(..).append(..).append(..));
}
collection.insertMany(docList);

this.close(conn);
}

public int delete() {
conn = this.getConn();
MongoDatabase db = conn.getDatabase("test");
MongoCollection<Document> collection = db.getCollection("ss");

// 单量删除
collection.deleteOne(new Document("name", "new-lt10"));
// 批量删除
DeleteResult deleteResult = collection.deleteMany(..);

this.close(conn);
// 返回影响文档数
return deleteResult.getDeletedCount();
}

public int update() {
conn = this.getConn();
MongoDatabase db = conn.getDatabase("test");
MongoCollection<Document> collection = db.getCollection("ss");

// 单量修改
collection.updateOne(new Document("name", "lt10"),
new Document("$set", new Document("name", "new-lt10")));

// 批量修改
UpdateResult updateResult = collection.updateMany(new Document("name", "lt10"),
new Document("$set", new Document("name", "new-lt10")));

this.close(conn);
return updateResult.getModifiedCount()
}

public void list() {
conn = this.getConn();
MongoDatabase db = conn.getDatabase("test");
MongoCollection<Document> collection = db.getCollection("ss");

// 查询集合大小
collection.count();

// 查询集合的第一个文档
Document myDoc = collection.find().first();
myDoc.toJson();

// 查询集合的全部文档
MongoCursor<Document> cursor = collection.find().iterator();
while (cursor.hasNext()) {
cursor.next().toJson();
}

// 查询集合的全部文档
for (Document cur : collection.find()) {
cur.toJson();
}

// 按条件查询集合的指定文档
MongoCursor<Document> cursor = collection.find(
new Document("name", "lt")).iterator();
while (cursor.hasNext()) {
cursor.next().toJson();
}

// 使用QueryBuilder按条件查询,找到name叫lt,且sex为man的记录
QueryBuilder queryBuilder =
QueryBuilder.start("name").is("lt").and("set").is("man");

this.close(conn);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: