1. 程式人生 > >MongoDB十分鐘搞定CRUD

MongoDB十分鐘搞定CRUD

一、環境準備
MongoDB環境安裝參照 MongoDBWindows平臺安裝
二、建立專案,新增MongoDB驅動依賴Jar

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.4.0</version>
</dependency>

三、建立連線

// To directly connect to a single MongoDB server
// (this will not
auto-discover the primary even if it's a member of a replica set) MongoClient mongoClient = new MongoClient(); // or MongoClient mongoClient = new MongoClient( "localhost" ); // or MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // or, to connect to a replica set, with auto-discovery of
the primary, supply a seed list of members MongoClient mongoClient = new MongoClient( Arrays.asList(new ServerAddress("localhost", 27017), new ServerAddress("localhost", 27018), new ServerAddress("localhost", 27019))); // or use a connection string MongoClientURI connectionString = new
MongoClientURI("mongodb://localhost:27017,localhost:27018,localhost:27019"); MongoClient mongoClient = new MongoClient(connectionString); MongoDatabase database = mongoClient.getDatabase("mydb");

這是驅動api提供的幾種連線資料庫的方式,選一個自己喜歡的即可
四、開始CRUD

  • insert
    這裡先插入一點點資料方便後面測試
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        MongoDatabase mongoDatabase = mongoClient.getDatabase("dbtest"); 
        MongoCollection<Document> collection = mongoDatabase.getCollection("users");
        for (int i = 0; i < 100000; i++) {
                Document document=  new Document();
                document.append("name", "white"+i);
                document.append("age",i);
                document.append("sex",i%2);
                document.append("money",i*10);
                // insert into users(....)
                collection.insertOne(document);
        } 
        mongoClient.close();
  • query
    ①條件查詢
    @Test
    public void findByCondition(){
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        MongoDatabase db = mongoClient.getDatabase("dbtest"); 
        MongoCollection<Document> collection = db.getCollection("users");
        // select * from user
        collection.find();
        // select top 1 * from user where name = 'white11'
        collection.find(Filters.eq("name", "white11")).first();
        // select * from user where age < 10
        collection.find(Filters.lt("age", 10));
        // select * from user where age>= 70 and age<=100
        collection.find(Filters.and(Filters.lte("age", 100),Filters.gte("age", 70)));
        mongoClient.close();
    }
②排序
    @Test
    public void findBySort(){
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        MongoDatabase db = mongoClient.getDatabase("dbtest"); 
        MongoCollection<Document> collection = db.getCollection("users");
        // select * from user where age>= 70 and age<=100 order by sex desc ,age desc
        FindIterable<Document> sort = collection.find(Filters.and(Filters.lte("age", 100),Filters.gte("age", 70))).sort(Indexes.descending("sex","age")).projection(new Document().append("_id", 0));
        for (Document document : sort) {
            System.out.println(document);
        }
        mongoClient.close();
    }
  • update
    @Test
    public void update(){
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        MongoDatabase db = mongoClient.getDatabase("dbtest"); 
        MongoCollection<Document> collection = db.getCollection("users");
        // udpate users set name = '大神' where name = 'white11'
        UpdateResult updateOne = collection.updateOne(Filters.eq("name", "white11"), new Document().append("$set",new Document("name", "大神")));

        UpdateResult updateMany = collection.updateMany(Filters.lt("age", 10), new Document().append("$inc", new Document().append("age", -100)));
        // 影響行數 
        System.out.println(updateMany.getModifiedCount());

        mongoClient.close();
    }
  • delete
    @Test
    public void delete(){
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        MongoDatabase db = mongoClient.getDatabase("dbtest"); 
        MongoCollection<Document> collection = db.getCollection("users");
        // delete users where name = 'white10'
        collection.deleteOne(Filters.eq("name", "white10"));
        // delete users where age < 10
        collection.deleteMany(Filters.lt("age", 10));
        mongoClient.close();
    }