当前位置: 首页 > news >正文

mongo java driver 3.2_MongoDB-JAVA-Driver 3.2版本常用代碼全整理(2) - 查詢

MongoDB的3.x版本Java驅動相對2.x做了全新的設計,類庫和使用方法上有很大區別。例如用Document替換BasicDBObject、通過Builders類構建Bson替代直接輸入$命令等,本文整理了基於3.2版本的常用增刪改查操作的使用方法。為了避免冗長的篇幅,分為增刪改、查詢、聚合、地理索引等幾部分。

先看用於演示的類的基本代碼

import static com.mongodb.client.model.Filters.*;

import static com.mongodb.client.model.Projections.*;

import static com.mongodb.client.model.Sorts.*;

import java.text.ParseException;

import java.util.Arrays;

import org.bson.BsonType;

import org.bson.Document;

import com.mongodb.Block;

import com.mongodb.MongoClient;

import com.mongodb.client.FindIterable;

import com.mongodb.client.MongoCollection;

import com.mongodb.client.MongoDatabase;

import com.mongodb.client.model.Filters;

import com.mongodb.client.model.Projections;

public class FindExamples {

public static void main(String[] args) throws ParseException {

//根據實際環境修改ip和端口

MongoClient mongoClient = new MongoClient("localhost", 27017);

MongoDatabase database = mongoClient.getDatabase("lesson");

FindExamples client = new FindExamples(database);

client.show();

mongoClient.close();

}

private MongoDatabase database;

public FindExamples(MongoDatabase database) {

this.database = database;

}

public void show() {

MongoCollection mc = database.getCollection("blog");

//每次執行前清空集合以方便重復運行

mc.drop();

//插入用於測試的文檔

Document doc1 = new Document("title", "good day").append("owner", "tom").append("words", 300)

.append("comments", Arrays.asList(new Document("author", "joe").append("score", 3).append("comment", "good"), new Document("author", "white").append("score", 1).append("comment", "oh no")));

Document doc2 = new Document("title", "good").append("owner", "john").append("words", 400)

.append("comments", Arrays.asList(new Document("author", "william").append("score", 4).append("comment", "good"), new Document("author", "white").append("score", 6).append("comment", "very good")));

Document doc3 = new Document("title", "good night").append("owner", "mike").append("words", 200)

.append("tag", Arrays.asList(1, 2, 3, 4));

Document doc4 = new Document("title", "happiness").append("owner", "tom").append("words", 1480)

.append("tag", Arrays.asList(2, 3, 4));

Document doc5 = new Document("title", "a good thing").append("owner", "tom").append("words", 180)

.append("tag", Arrays.asList(1, 2, 3, 4, 5));

mc.insertMany(Arrays.asList(doc1, doc2, doc3, doc4, doc5));

//測試: 查詢全部

FindIterable iterable = mc.find();

printResult("find all", iterable);

//TODO: 將在這里填充更多查詢示例

}

//打印查詢的結果集

public void printResult(String doing, FindIterable iterable) {

System.out.println(doing);

iterable.forEach(new Block() {

public void apply(final Document document) {

System.out.println(document);

}

});

System.out.println("------------------------------------------------------");

System.out.println();

}

}

如上面代碼所示,把所有的查詢操作集中在show()方法中演示,並且在執行后打印結果集以觀察查詢結果。下面來填充show()方法

注意需要靜態導入

import static com.mongodb.client.model.Filters.*;

import static com.mongodb.client.model.Projections.*;

import static com.mongodb.client.model.Sorts.*;

//創建單字段索引

mc.createIndex(new Document("words", 1));

//創建組合索引(同樣遵循最左前綴原則)

mc.createIndex(new Document("title", 1).append("owner", -1));

//創建全文索引

mc.createIndex(new Document("title", "text"));

//查詢全部

FindIterable iterable = mc.find();

printResult("find all", iterable);

//查詢title=good

iterable = mc.find(new Document("title", "good"));

printResult("find title=good", iterable);

//查詢title=good and owner=tom

iterable = mc.find(new Document("title", "good").append("owner", "tom"));

printResult("find title=good and owner=tom", iterable);

//查詢title like %good% and owner=tom

iterable = mc.find(and(regex("title", "good"), eq("owner", "tom")));

printResult("find title like %good% and owner=tom", iterable);

//查詢全部按title排序

iterable = mc.find().sort(ascending("title"));

printResult("find all and ascending title", iterable);

//查詢全部按owner,title排序

iterable = mc.find().sort(ascending("owner", "title"));

printResult("find all and ascending owner,title", iterable);

//查詢全部按words倒序排序

iterable = mc.find().sort(descending("words"));

printResult("find all and descending words", iterable);

//查詢owner=tom or words>350

iterable = mc.find(new Document("$or", Arrays.asList(new Document("owner", "tom"), new Document("words", new Document("$gt", 350)))));

printResult("find owner=tom or words>350", iterable);

//返回title和owner字段

iterable = mc.find().projection(include("title", "owner"));

printResult("find all include (title,owner)", iterable);

//返回除title外的其他字段

iterable = mc.find().projection(exclude("title"));

printResult("find all exclude title", iterable);

//不返回_id字段

iterable = mc.find().projection(excludeId());

printResult("find all excludeId", iterable);

//返回title和owner字段且不返回_id字段

iterable = mc.find().projection(fields(include("title", "owner"), excludeId()));

printResult("find all include (title,owner) and excludeId", iterable);

//內嵌文檔匹配

iterable = mc.find(new Document("comments.author", "joe"));

printResult("find comments.author=joe", iterable);

//一個錯誤的示例, 想查詢評論中包含作者是white且分值>2的, 返回結果不符合預期

iterable = mc.find(new Document("comments.author", "white").append("comments.score", new Document("$gt", 2)));

printResult("find comments.author=white and comments.score>2 (wrong)", iterable);

//上面的需求正確的寫法

iterable = mc.find(Projections.elemMatch("comments", Filters.and(Filters.eq("author", "white"), Filters.gt("score", 2))));

printResult("find comments.author=white and comments.score>2 using elemMatch", iterable);

//查找title以good開頭的, 並且comments只保留一個元素

iterable = mc.find(Filters.regex("title", "^good")).projection(slice("comments", 1));

printResult("find regex ^good and slice comments 1", iterable);

//全文索引查找

iterable = mc.find(text("good"));

printResult("text good", iterable);

//用Filters構建的title=good

iterable = mc.find(eq("title", "good"));

printResult("Filters: title eq good", iterable);

//$in 等同於sql的in

iterable = mc.find(in("owner", "joe", "john", "william"));

printResult("Filters: owner in joe,john,william", iterable);

//$nin 等同於sql的not in

iterable = mc.find(nin("owner", "joe", "john", "tom"));

printResult("Filters: owner nin joe,john,tom", iterable);

//查詢內嵌文檔

iterable = mc.find(in("comments.author", "joe", "tom"));

printResult("Filters: comments.author in joe,tom", iterable);

//$ne 不等於

iterable = mc.find(ne("words", 300));

printResult("Filters: words ne 300", iterable);

//$and 組合條件

iterable = mc.find(and(eq("owner", "tom"), gt("words", 300)));

printResult("Filters: owner eq tom and words gt 300", iterable);

//較復雜的組合

iterable = mc.find(and(or(eq("words", 300), eq("words", 400)), or(eq("owner", "joe"), size("comments", 2))));

printResult("Filters: (words=300 or words=400) and (owner=joe or size(comments)=2)", iterable);

//查詢第2個元素值為2的數組

iterable = mc.find(eq("tag.1", 2));

printResult("Filters: tag.1 eq 2", iterable);

//查詢匹配全部值的數組

iterable = mc.find(all("tag", Arrays.asList(1, 2, 3, 4)));

printResult("Filters: tag match all (1, 2, 3, 4)", iterable);

//$exists

iterable = mc.find(exists("tag"));

printResult("Filters: exists tag", iterable);

iterable = mc.find(type("words", BsonType.INT32));

printResult("Filters: type words is int32", iterable);

這里列出的查詢方式可以覆蓋到大部分開發需求,更多查詢需求請參考官方文檔。

(完)

相关文章:

  • java中标记怎么用_在Java中使用标记(标签)
  • java结束sql链接_数据查询时报出java.sql.SQLException: 关闭的连接
  • java 控制台画表格_Java库在控制台上构建和打印表格?
  • 242. valid anagram java_Leetcode242 Valid Anagram JAVA语言
  • java 查找大写字母_Java实现给定一个包含大写字母和小写字母的字符串,找到通过这些...
  • java 绘图球的移动_在Java上绘制2个朝不同方向移动的球,但一个消失了
  • php中购物车结算代码,jquery购物车结算功能实现方法
  • php.ini配置 耗时,配置PHP.INI监测服务器的脚本耗时
  • java自动生成测试与评估,jmeter如何自动生成测试报告
  • php memcached存储对象,从memcached获取对象并在PHP中设置为self
  • java阅读安卓,java – 如何在android中逐行阅读?
  • plotm matlab,MATLAB画地图的工具:worldmap和m_map
  • matlab不能盗版吗,matlab为了防止盗版,会不会篡改程序运行结果?这是明证
  • matlab 复权数据,〖Matlab〗基于通达信股价数据的复权处理(fantuanxiaot版本)
  • 微信小程序向php传递数据,微信小程序 跳转传递数据的方法
  • 【159天】尚学堂高琪Java300集视频精华笔记(128)
  • 【React系列】如何构建React应用程序
  • 3.7、@ResponseBody 和 @RestController
  • 5分钟即可掌握的前端高效利器:JavaScript 策略模式
  • android图片蒙层
  • Apache的基本使用
  • Docker 笔记(1):介绍、镜像、容器及其基本操作
  • Electron入门介绍
  • java多线程
  • java正则表式的使用
  • leetcode378. Kth Smallest Element in a Sorted Matrix
  • Nacos系列:Nacos的Java SDK使用
  • nfs客户端进程变D,延伸linux的lock
  • Octave 入门
  • SAP云平台运行环境Cloud Foundry和Neo的区别
  • SpingCloudBus整合RabbitMQ
  • Vue组件定义
  • Zsh 开发指南(第十四篇 文件读写)
  • 关于 Linux 进程的 UID、EUID、GID 和 EGID
  • 机器人定位导航技术 激光SLAM与视觉SLAM谁更胜一筹?
  • 技术攻略】php设计模式(一):简介及创建型模式
  • 简单易用的leetcode开发测试工具(npm)
  • 聊聊redis的数据结构的应用
  • 算法-图和图算法
  • 腾讯优测优分享 | 你是否体验过Android手机插入耳机后仍外放的尴尬?
  • 赢得Docker挑战最佳实践
  • 这几个编码小技巧将令你 PHP 代码更加简洁
  • 积累各种好的链接
  • # 20155222 2016-2017-2 《Java程序设计》第5周学习总结
  • #git 撤消对文件的更改
  • (html5)在移动端input输入搜索项后 输入法下面为什么不想百度那样出现前往? 而我的出现的是换行...
  • (附源码)spring boot校园健康监测管理系统 毕业设计 151047
  • (九)One-Wire总线-DS18B20
  • (四)鸿鹄云架构一服务注册中心
  • (转)Spring4.2.5+Hibernate4.3.11+Struts1.3.8集成方案一
  • ****** 二十三 ******、软设笔记【数据库】-数据操作-常用关系操作、关系运算
  • ***原理与防范
  • .cfg\.dat\.mak(持续补充)
  • .NET 使用配置文件
  • .NET/C# 避免调试器不小心提前计算本应延迟计算的值