MongoDB常用Java Api(3.6)

385 阅读2分钟

1.连接到单个mongodb实例

(1)连接到端口上localhost上运行的MongoDB实例
MongoClient mongoClient = MongoClients.create();

(2)指定主机名以连接到端口上指定主机上运行的MongoDB实例

MongoClient mongoClient = MongoClients.create(
    MongoClientSettings.builder()
    .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress("hostOne")))).build());

(3)指定主机名和端口

MongoClient mongoClient = MongoClients.create(
 MongoClientSettings.builder()
 .applyToClusterSettings(builder ->builder.hosts(Arrays.asList(new ServerAddress("hostOne", 27018)))).build());

(4)指定ConnectionString

MongoClient mongClient=MongClients.create("mongodb://hostOne:27017,hostTwo:27018");

2.获取数据库对象

MongoDatabase database=mongoClient.getDatabase(dataBaseName);

3.获取集合对象

MongoCollection<Document> collection=database.getCollection(collectionName);

4.创建文档对象

{
"name" : "MongoDB",
"type" : "database",
"count" : 1,
"versions": [ "v3.2", "v3.0", "v2.6" ],
"info" : { x : 203, y : 102 }
}

Document document = new Document("name", "MongoDB")
        .append("type", "database")
        .append("count", 1)
        .append("versions", Arrays.asList("v3,2", "v3.0", "v2.6"))
        .append("info", new Document("x", 203)
        .append("y", 102));

  collection.insertOne(document);--插入单个文档对象

  collection.insertMany(documents);--插入多个文档对象

5.计算集合中的文档数

collection.countDocuments();

6.查询文档对象

(1)查询一个或者第一个文档对象

Document doc = collection.find().first();

(2)查询所有文档对象

MongoCursor<Document> cursor = collection.find().iterator();
try {
          while (cursor.hasNext()) {
                     System.out.println(cursor.next().toJson());
            }
} finally {
            cursor.close();
}

(3)通过过滤器(Filters)查询文档对象

collection.find(eq("name", "张三"));
Block<Document> printBlock = new Block<Document>() {
                        @Override
                       public void apply(final Document document) {
                                            System.out.println(document.toJson());
                       }
};
collection.find(gt("age", 12)).forEach(printBlock);
collection.find(and(gt("age", 12), lte("age", 30))).forEach(printBlock);

7.更新文档对象

(1)更新单个文档对象

collection.updateOne(eq("age", 10), new Document("$set", new Document("age", 100)));

(2)更新多个文档对象

UpdateResult updateResult = collection.updateMany(gt("age", 10), inc("age", 1));

8.删除文档对象

(1)删除单个文档对象

collection.deleteOne(gte("age", 10));

(2)删除多个文档对象

DeleteResult deleteResult = collection.deleteMany(gte("age", 10));

9.其他查询

(1) 根据sex分组,获取age最大值

Document groupDocument = new Document();
        groupDocument.put("_id", "$sex");
        groupDocument.put("max_age",new Document("$max","$age"));
        Document group = new Document("$group",groupDocument);
        documents.add(group);
        MongoCursor<Document> cursor = collection.aggregate(documents).iterator();

(2) 根据sex分组,根据age求和

Document groupDocument = new Document();
        groupDocument.put("_id", "$sex");
        groupDocument.put("sum_age",new Document("$sum","$age"));
        Document group = new Document("$group",groupDocument);
        documents.add(group);
        MongoCursor<Document> cursor = collection.aggregate(documents).iterator();

(3) 查询sex 为FeMale按age降序,并取第11-20条数据

MongoCursor<Document> cursor = collection.find(new Document("sex", "FeMale"))
                .sort(new Document("age", -1)).skip(10).limit(10).iterator();

(4) 去除sex字段的重复值

MongoCursor<String> cursor = collection.distinct("sex", String.class).iterator();

(5) 使用$match作查询 注意$match一定要放在$group之前

Document filterDocument = new Document("age", new Document("$gte", 10))
                .append("age", new Document("$lt", 20)).append("sex", "FeMale");
Document matchDocument = new Document();
matchDocument.put("$match", filterDocument);
Document groupDocument = new Document();
groupDocument.put("_id", "$_id");
groupDocument.put("max_age",new Document("$max","$age"));
Document group = new Document("$group",groupDocument);
documents.add(matchDocument);
documents.add(project);
documents.add(group);
MongoCursor<Document> cursor = collection.aggregate(documents).iterator();

(6) 查询返回指定字段(_id默认返回)

Document filterDocument = new Document("age", new Document("$gte", 10))
                .append("age", new Document("$lt", 20)).append("sex", "FeMale");
// 1返回值, 0不返回值
Document projectDocument = new Document("_id", 0).append("age", 1);
MongoCursor<Document> cursor = collection.find(filterDocument).projection(projectDocument).iterator();

(7) and查询

MongoCursor<Document> cursor = collection.find(
                and(gt("age", 20), lte("age", 40))).iterator();

(8) or查询

MongoCursor<Document> cursor = collection.find(
                or(gt("age", 100), lte("age", 10))).iterator();

10.索引

(1) 创建索引 1 升序索引 -1 降序索引

String indexName = collection.createIndex(new Document("age", 1));

List<IndexModel> indexModelList = new ArrayList<>();
indexModelList.add(new IndexModel(new Document("age", 1)));
indexModelList.add(new IndexModel(new Document("sex", -1)));
collection.createIndexes(indexModelList);

(2) 删除单个索引

collection.dropIndex(new Document("age", 1));

collection.dropIndex(indexName);

(3) 删除集合所有索引(不包括_id的索引)

collection.dropIndexes();

(4) 查看集合所有索引

MongoCursor<Document> cursor = collection.listIndexes().iterator();