数据库.MongoDB.Java样例

时间:2021-07-10 16:01:54

1.先在MongoDB官网下载Java驱动包

MongoDB Java Driver:

http://mongodb.github.io/mongo-java-driver/

JAR包下载列表

https://oss.sonatype.org/content/repositories/releases/org/mongodb/mongodb-driver/3.5.0/

2.程序样例

 package com.test;

 import java.util.Arrays;

 import org.bson.Document;

 import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase; public class MongoDb_Test2 {
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient( "localhost" , );
MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("test");
System.out.println(collection.count());
Document doc = new Document("name", "MongoDB")
.append("type", "database")
.append("count", )
.append("versions", Arrays.asList("v3.2", "v3.0", "v2.6"))
.append("info", new Document("x", ).append("y", ));
collection.insertOne(doc);
System.out.println(collection.count());
System.out.println("done!");
}
}

执行结果:

数据库.MongoDB.Java样例

读取数据样例

        FindIterable<Document> iterable = collection.find().limit();
MongoCursor<Document> cursor = iterable.iterator();
if(cursor.hasNext()) {
Document user = (Document)cursor.next();
System.out.println(user.get("name"));
System.out.println(user.toString());
}
cursor.close();