MongoDB常用Java Api

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");

3.获取数据库对象

MongoDatabase database = mongoClient.getDatabase(dataBaseName);

4.获取集合对象

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

5.创建文档对象
{
"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);--插入多个文档对象

6.计算集合中的文档数

collection.countDocuments();

7.查询文档对象

(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);

8.更新文档对象

collection.updateOne(eq("age", 10), new Document("$set", new Document("age", 100)));--更新单个文档对象

UpdateResult updateResult = collection.updateMany(gt("age", 10), inc("age", 1));--更新多个文档对象

9.删除文档对象

collection.deleteOne(gte("age", 10)).--删除单个文档对象

DeleteResult deleteResult = collection.deleteMany(gte("age", 10));--删除多个文档对象

10.其他查询
(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();

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、MongoDB简介 1.概述 ​ MongoDB是一个基于分布式文件存储的数据库,由C++语言编写。旨在为WE...
    郑元吉阅读 4,574评论 0 2
  • NoSql数据库优缺点 在优势方面主要体现在下面几点: 简单的扩展 快速的读写 低廉的成本 灵活的数据模型 在不足...
    dreamer_lk阅读 7,748评论 0 6
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 13,150评论 0 13
  • MongoDB安装很简单,无需下载源文件,可以直接用apt-get命令进行安装。 打开终端,输入以下命令: sud...
    泪滴在琴上阅读 10,466评论 0 6
  • 1、MongoDB概念解析: 2、数据库: "show dbs"命令可以显示所有数据的列表。"db"命令可以显示当...
    妮妮爱布阅读 3,764评论 0 0