3.1 MongoDB through the Java
http://mongodb.github.io/mongo-java-driver/3.12/driver/getting-started/quick-start/
3.1.1 connecting
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.12.7</version>
</dependency>
private ServerAddress serverAddress = new ServerAddress("101.132.251.198", 27017);
private MongoCredential credential = MongoCredential.createCredential("root", "tutorial", "root".toCharArray());
private MongoClient mongoClient = new MongoClient(serverAddress, credential, MongoClientOptions.builder().build());
private MongoDatabase database = mongoClient.getDatabase("tutorial");
private MongoCollection<Document> users = database.getCollection("users");
Create a Document
{
"name" : "MongoDB",
"type" : "database",
"count" : 1,
"versions": [ "v3.2", "v3.0", "v2.6" ],
"info" : { x : 203, y : 102 }
}
Document doc = new Document("name", "MongoDB").append("type", "database")
.append("count", 1)
.append("versions", Arrays.asList("v3.2", "v3.0", "v2.6"))
.append("info", new Document("x", 203).append("y", 102));
Insert a Document
users.insertOne(doc);
Insert Multiple Documents
@Test
public void testInsertMultiple(){
ArrayList<Document> documents = new ArrayList<>();
for (int i = 0; i < 100; i++) {
documents.add(new Document("i", i));
}
users.insertMany(documents);
}
Count Documents in A Collection
@Test
public void testCount() {
System.out.println(users.countDocuments());
}
Query the Collection
Find the First Document in a Collection
@Test
public void testQuery() {
Document myDoc = users.find().first();
System.out.println(myDoc.toJson());
}
Find All Documents in a Collection
@Test
public void testQuery() {
MongoCursor<Document> cursor = users.find().iterator();
try {
while (cursor.hasNext()){
System.out.println(cursor.next().toJson());
}
}finally {
cursor.close();
}
}
避免用foreach循环迭代遍历,因为如果循环提前结束,应用程序可能会泄露游标
Specify a Query Filter
Get A Single Document That Matches a Filter
@Test
public void testQueryFilter() {
Document myDoc = users.find(Filters.eq("i", 71)).first();
System.out.println(myDoc.toJson());
}
Get All Documents That Match a Filter
@Test
public void testQueryFilter() {
Block<Document> printBlock = new Block<Document>(){
@Override
public void apply(Document document) {
System.out.println(document.toJson());
}
};
users.find(Filters.gt("i", 50)).forEach(printBlock);
users.find(Filters.and(Filters.gt("i", 50), Filters.lte("i", 100))).forEach(printBlock);
}
Update Documents
- updateOne
- updateMany
返回值为UpdateResult,提供了关于文档更新的数量信息
Update a Single Document
@Test
public void testUpdate() {
users.updateOne(Filters.eq("i", 10), new Document("$set", new Document("i", 110)));
Document documents = users.find(new Document("i", 110)).first();
System.out.println(documents.toJson());
}
Update Multiple Documents
@Test
public void testUpdate() {
// 下面的例子将所有文件的i值增加100,其中i小于100的值:
UpdateResult updateResult = users.updateMany(lt("i", 100), Updates.inc("i", 100));
System.out.println(updateResult.getModifiedCount());
}
Delete Documents
- deleteOne
deleteMany
@Test
public void testDelete() {
DeleteResult deleteResult = users.deleteMany(gte("i", 100));
System.out.println(deleteResult.getDeletedCount());
}
Create Indexes
For an ascending index type, specify 1 for
. - For a descending index type, specify -1 for
. @Test
public void testCreateIndexes() {
users.createIndex(new Document("i", 1));
}