先引入mongo-java-dirver驱动
1 2 3 4 5 6 | <!-- mongo-java-dirver --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version> 3.4 . 2 </version> </dependency> |
代码操作演示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | package com.simple.database.test; import java.util.ArrayList; import java.util.List; import org.bson.Document; import org.bson.conversions.Bson; 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 com.mongodb.client.model.Filters; /** * java操作MongoDB * @author root */ public class HelloMongoDB { public static void main(String[] args) { try { // 1、连接到MongoDB服务 MongoClient mc = new MongoClient( "127.0.0.1" , 27017 ); // 2、连接到指定数据库 MongoDatabase db = mc.getDatabase( "demodb" ); // 3、创建集合 // db.createCollection("simplelife"); // 4、获取集合 MongoCollection<Document> collection = db.getCollection( "users" ); // 5、插入文档数据 // insertCollectionData(collection); // 6、查询文档数据 findCollectionData(collection); // 7、更新文档数据 // 将文档中likes=100的文档修改为likes=200 updateCollectionData(collection); // 8、删除第一个文档数据 collection.deleteMany(Filters.eq( "likes" , 200 )); collection.deleteOne(Filters.eq( "likes" , 100 )); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getClass().getName() + "……" + e.getMessage()); } } private static void updateCollectionData( MongoCollection<Document> collection) { Bson filter = Filters.eq( "likes" , 100 ); Document update = new Document( "$set" , new Document( "likes" , 200 )); collection.updateMany(filter, update); } private static void findCollectionData(MongoCollection<Document> collection) { FindIterable<Document> findIterable = collection.find(); MongoCursor<Document> mongoCursor = findIterable.iterator(); while (mongoCursor.hasNext()){ System.out.println(mongoCursor.next()); } } /** * 插入文档 1、创建文档org.bson.Document参数为key-value的格式 * 2、创建文档集合List<Document> * 3、将文档集合插入数据库集合:mongoCollection.insertMany(List<Document>) * 插入单个文档可以用 :mongoCollection.insertOne(Document) */ private static void insertCollectionData( MongoCollection<Document> collection) { Document document = new Document( "title" , "MongoDB" ); document.append( "description" , "database" ).append( "likes" , 100 ) .append( "by" , "Fly" ); List<Document> documents = new ArrayList<>(); documents.add(document); collection.insertMany(documents); System.out.println( "文档插入成功!" ); } } |