1.1:连接Mongodb并进入sore数据库
MongoClient conn=null;
static MongoDatabase db=null;
public Mongodb1(String dbName) {
conn = new MongoClient("127.0.0.1");
db = conn.getDatabase(dbName);
}
Mongodb1 mongodb = new Mongodb1("sore");//选择sore数据库
1.2通过Mongodbdatabase对象db的方法创建集合
db.createCollection("students");//创建集合
Document doc = new Document();
doc.put("name", "lisi");
doc.put("age", 25);
也可以创建关于数组的集合:
List<String> books = new ArrayList<String>();
books.add("JAVA");
books.add("python");
books.add("C++");
books.add("JSP");
//将数组添加到集合中
doc.put("books1", books);
完整代码:
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
public class Mongodb1 {
MongoClient conn=null;
static MongoDatabase db=null;
public Mongodb1(String dbName) {
conn = new MongoClient("127.0.0.1");
db = conn.getDatabase(dbName);
}
public static void main(String[] args) {
Mongodb1 mongodb = new Mongodb1("sore");
db.createCollection("students");//创建集合
Document doc = new Document();
doc.put("name", "lisi");
doc.put("age", 25);
List<String> books = new ArrayList<String>();
books.add("JAVA");
books.add("python");
books.add("C++");
books.add("JSP");
//将数组添加到集合中
doc.put("books1", books);
MongoCollection<Document> coll1= db.getCollection("students");
//在students库上插入一条文档
coll1.insertOne(doc);
FindIterable<Document> findIter=coll1.find();
MongoCursor<Document> cur=findIter.iterator();
//通过游标来访问文档数据
while (cur.hasNext()) {
Document doc1=cur.next();
System.out.println(doc1.get("name")+"=============="+doc1.get("books1")+"============"+doc1.get("age"));
}
}
}