1. 程式人生 > >數據庫.MongoDB.Java樣例

數據庫.MongoDB.Java樣例

slist rgs oss lease 執行 bson 下載列表 releases ron

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 }

執行結果:

技術分享

數據庫.MongoDB.Java樣例