当前位置:Gxlcms > 数据库问题 > MongoDB Java

MongoDB Java

时间:2021-07-01 10:21:17 帮助过:12人阅读

dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.0</version> </dependency>
//连接 MongoDB
MongoClient client=new MongoClient("localhost",27017);
//连接数据库
MongoDatabase database=client.getDatabase("test1");
System.out.println("connect success");
//创建集合
database.createCollection("test3");
//获取集合
MongoCollection<Document> collection=database.getCollection("hjy");

/**
         * 插入文档,先创建文档,再插入
         */
//创建文档,可以是map,可以是key-value
System.out.println("insert document...");
Document document=new Document("title","mongodb")
    .append("description","database")
    .append("likes",5000)
    .append("by","hjy1");
List<Document> documents=new ArrayList<Document>();
documents.add(document);
//插入单个文档用 insertOne
collection.insertMany(documents);
System.out.println("insert success...");

/**
         * 查询所有文档
         */
System.out.println("query all document...");
FindIterable<Document> findIterable=collection.find();
MongoCursor<Document> mongoCursor=findIterable.iterator();
while(mongoCursor.hasNext()){
    System.out.println(mongoCursor.next());
}
System.out.println("query all document success...");

/**
         *更新文档,更新likes=100的文档为likes=501
         */
System.out.println("update document...");
collection.updateMany(Filters.eq("likes",100),
                     new Document("$set",new Document("likes",501)));
System.out.println("update success...");

/**
         * 删除文档,删除likes=1005的文档
         */
System.out.println("delete document...");
collection.deleteOne(Filters.eq("likes",1005));
System.out.println("delete success...");

//关闭连接
client.close();

 

MongoDB Java

标签:$set   驱动   filters   collect   add   mongodb   query   style   filter   

人气教程排行