MongoDB 3.0 for java (二、java操纵MongoDB)
2017-07-19 21:44:47    789   
lightingfire
+++++++ 20160404 begin+++++++
maven环境:
<dependency>
	<groupId>org.mongodb</groupId>
	<artifactId>mongodb-driver</artifactId>
	<version>3.2.2</version>
</dependency>

+++++++ 20160404 end+++++++

 
import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class TestMongo {
    public static void main(String[] args) {
        MongoClient client = null;
        ServerAddress serverAddress = new ServerAddress("115.28.246.12",
                27017);
        List<ServerAddress> seeds = new ArrayList<ServerAddress>();
        seeds.add(serverAddress);
        MongoCredential credentials = MongoCredential
                .createScramSha1Credential("admin", "admin",
                        "abc123,admin".toCharArray());
        List<MongoCredential> credentialsList = new ArrayList<MongoCredential>();
        credentialsList.add(credentials);
        client = new MongoClient(seeds, credentialsList);

        //获取db(如果存在db,则获取,如果不存在,则创建,但是必须在创建集合后,db才真正创建)
        MongoDatabase myTestDB = client.getDatabase("myTest");
        //创建集合
        myTestDB.createCollection("test");
        //定义文档(两层结构组成)
        Document doc = new Document("name", "MongoDB")
        .append("type", "database")
        .append("count", 1)
        .append("info", new Document("x", 203).append("y", 102));

        //插入文档数据
        myTestDB.getCollection("test").insertOne(doc);

        //获取集合
        MongoCollection<Document> testCollection=myTestDB.getCollection("test");
        //获取结合中的所有文档
        List<Document> testDocs = testCollection.find().into(new ArrayList<Document>());
        System.out.println(testDocs);

        //更新集合中count为1的文档,count设置为2
        testCollection.updateMany(Filters.eq("count", 1), new Document("$set",new Document("count",2)));

        testDocs = testCollection.find().into(new ArrayList<Document>());
        System.out.println(testDocs);
        //删除count为2的所有文档
        testCollection.deleteMany(Filters.eq("count", 2));
        testDocs = testCollection.find().into(new ArrayList<Document>());
        System.out.println(testDocs);

    }
}

 

by 刘迎光@萤火虫工作室
OpenBI交流群:495266201
MicroService 微服务交流群:217722918
mail: liuyg#liuyingguang.cn
博主首页(防止爬虫):http://blog.liuyingguang.cn
OpenBI问答社区:http://openbi.liuyingguang.cn/


Pre: docker-compose 安装TYK环境(4个Docker:dashboard、gateway、mongo、redis)

Next: mongodb3更新数据java.lang.IllegalArgumentException: Invalid BSON field name _id


Table of content