mongodb的相关命令我们这里不在赘述,因为其文档下写的非常清楚,也很容易懂。这里我们说一下其余java的整合,mongodb配置请查看官方文档
1.首先我们应该导入期相关依赖,
2.链接数据库以及部分操作,其余相差无几
public class mongodbTest {
public static void main(String args[]) {
try {
//MongoCredential credential = MongoCredential.createCredential(user, database, password);
//MongoClient mongoClient = new MongoClient(new ServerAddress("host1", 27017),
//Arrays.asList(credential));
// 链接mongodb服务
MongoClient mongoClient = new MongoClient("localhost", 27017);
// 链接数据库
MongoDatabase mgdb = mongoClient.getDatabase("mycol");
//创建集合
//database.createCollection("NewCollection",new CreateCollectionOptions().capped(true).sizeInBytes(0x100000));
MongoCollection<Document> coll = database.getCollection("myTestCollection");
for (String name : database.listCollectionNames()) {
System.out.println(name);
}
//插入文档
Document document = new Document("_id", 1999).append("title", "MongoDB Insert Demo")
.append("description","database")
.append("likes", 30)
.append("by", "yiibai point")
.append("url", "xxxxxxxxxxxxxxxxxxxxxxxxxxx");
collection.insertOne(document);
collection.find().forEach(printBlock);
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
static Block<Document> printBlock = new Block<Document>() {
public void apply(final Document document) {
System.out.println(document.toJson());
}
};
}