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.程序样例
1 package com.test; 2 3 import java.util.Arrays; 4 5 import org.bson.Document; 6 7 import com.mongodb.MongoClient; 8 import com.mongodb.client.MongoCollection; 9 import com.mongodb.client.MongoDatabase; 10 11 public class MongoDb_Test2 { 12 public static void main(String[] args) { 13 MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); 14 MongoDatabase database = mongoClient.getDatabase("mydb"); 15 MongoCollection<Document> collection = database.getCollection("test"); 16 System.out.println(collection.count()); 17 Document doc = new Document("name", "MongoDB") 18 .append("type", "database") 19 .append("count", 1) 20 .append("versions", Arrays.asList("v3.2", "v3.0", "v2.6")) 21 .append("info", new Document("x", 203).append("y", 102)); 22 collection.insertOne(doc); 23 System.out.println(collection.count()); 24 System.out.println("done!"); 25 } 26 }
执行结果:
读取数据样例
FindIterable<Document> iterable = collection.find().limit(1); 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();