MongoDB - 比较查询操作符$eq | 数组查询操作符 $eleMatch

文章目录

    • 1. $eq 比较查询操作符
        • 1.1 基本类型字段
        • 1.2 嵌入式文档字段
        • 1.3 数组字段
    • 2. $eleMatch 数组查询操作符
        • 2.1 基本类型数组字段
        • 2.2 基本类型数组字段
        • 2.3 嵌入式文档数组字段
        • 2.4 嵌入式文档数组字段

1. $eq 比较查询操作符

$eq 操作符匹配字段值等于指定值的文档。

db.colletion.find({{ <field>: { $eq: <value> } }
})

$eq 运算符等同于下面的形式,但 <value> 是正则表达式的情况除外。

db.colletion.find({{ field: <value> }
})
1.1 基本类型字段

构造测试数据 :

db.inventory.drop()db.inventory.insertMany( [{ _id: 1, item: { name: "ab", code: "123" }, qty: 15, tags: [ "A", "B", "C" ] },{ _id: 2, item: { name: "cd", code: "123" }, qty: 20, tags: [ "B" ] },{ _id: 3, item: { name: "ij", code: "456" }, qty: 25, tags: [ "A", "B" ] },{ _id: 4, item: { name: "xy", code: "456" }, qty: 30, tags: [ "B", "A" ] },{ _id: 5, item: { name: "mn", code: "000" }, qty: 20, tags: [ [ "A", "B" ], "C" ] }
] )

查询 qty=20 的所有文档:

db.inventory.find({qty: {$eq: 20}
})db.inventory.find({qty: 20
})
// 1
{"_id": 2,"item": {"name": "cd","code": "123"},"qty": 20,"tags": ["B"]
}// 2
{"_id": 5,"item": {"name": "mn","code": "000"},"qty": 20,"tags": [["A","B"],"C"]
}
@Document(collection = "inventory")
@Data
public class Inventory {@Idprivate int id;private Item item;private int qty;private List<Object> tags;@Datapublic static class Item {private String name;private String code;}
}@Test
public void queryTest() {//构造查询条件Query query = new Query();query.addCriteria(Criteria.where("qty").is(20));//执行查询 List<Inventory> inventoryList = mongoTemplate.find(query, Inventory.class);inventoryList.forEach(System.out::println);//Inventory(id=2, item=Inventory.Item(name=cd, code=123), qty=20, tags=[B])//Inventory(id=5, item=Inventory.Item(name=mn, code=000), qty=20, tags=[[A, B], C])
}
1.2 嵌入式文档字段

构造测试数据 :

db.inventory.drop()db.inventory.insertMany( [{ _id: 1, item: { name: "ab", code: "123" }, qty: 15, tags: [ "A", "B", "C" ] },{ _id: 2, item: { name: "cd", code: "123" }, qty: 20, tags: [ "B" ] },{ _id: 3, item: { name: "ij", code: "456" }, qty: 25, tags: [ "A", "B" ] },{ _id: 4, item: { name: "xy", code: "456" }, qty: 30, tags: [ "B", "A" ] },{ _id: 5, item: { name: "mn", code: "000" }, qty: 20, tags: [ [ "A", "B" ], "C" ] }
] )

查询 “item.name”=“ab” 的所有文档:

db.inventory.find({"item.name": {$eq: "ab"}
})db.inventory.find({"item.name": "ab"
})
// 1
{"_id": 1,"item": {"name": "ab","code": "123"},"qty": 15,"tags": ["A","B","C"]
}
@Test
public void queryTest() {//构造查询条件Query query = new Query();query.addCriteria(Criteria.where("item.name").is("ab"));//执行查询List<Inventory> inventoryList = mongoTemplate.find(query, Inventory.class);inventoryList.forEach(System.out::println);//Inventory(id=1, item=Inventory.Item(name=ab, code=123), qty=15, tags=[A, B, C])
}
1.3 数组字段

构造测试数据 :

db.inventory.drop()db.inventory.insertMany([{ "_id" : 1, "item" : "abc1", description: "product 1", qty: 300 },{ "_id" : 2, "item" : "abc2", description: "product 2", qty: 200 },{ "_id" : 3, "item" : "xyz1", description: "product 3", qty: 250 },{ "_id" : 4, "item" : "VWZ1", description: "product 4", qty: 300 },{ "_id" : 5, "item" : "VWZ2", description: "product 5", qty: 180 }
])

查询 tags 数组包含 “A” 的所有文档:

db.inventory.find({"tags": {$eq: "A"}
})db.inventory.find({"tags": "A"
})
// 1
{"_id": 1,"item": {"name": "ab","code": "123"},"qty": 15,"tags": ["A","B","C"]
}// 2
{"_id": 3,"item": {"name": "ij","code": "456"},"qty": 25,"tags": ["A","B"]
}// 3
{"_id": 4,"item": {"name": "xy","code": "456"},"qty": 30,"tags": ["B","A"]
}
@Test
public void queryTest() {//构造查询条件Query query = new Query();query.addCriteria(Criteria.where("tags").is("A"));//执行查询List<Inventory> inventoryList = mongoTemplate.find(query, Inventory.class);//打印inventoryList.forEach(System.out::println);//Inventory(id=1, item=Inventory.Item(name=ab, code=123), qty=15, tags=[A, B, C])//Inventory(id=3, item=Inventory.Item(name=ij, code=456), qty=25, tags=[A, B])//Inventory(id=4, item=Inventory.Item(name=xy, code=456), qty=30, tags=[B, A])
}

2. $eleMatch 数组查询操作符

$elemMatch 操作符匹配包含数组字段的文档,该字段至少有一个元素与所有指定的查询条件匹配。

db.collection.find({ arrayField: { $elemMatch: { condition1, condition2 } } })
2.1 基本类型数组字段

构造测试数据:

db.student.drop()db.student.insertMany([{ _id: 1, scores: [ 82, 85, 88 ] },{ _id: 2, scorse: [ 75, 88, 89 ] }
])

查询 scores 数组中至少包含一个大于等于80并且小于85的文档:

db.student.find({ scores: { $elemMatch: { $gte: 80, $lt: 85 } } 
})
// 1
{"_id": 1,"scores": [82,85,88]
}
@Data
@Document(collection = "students")
public class Student {@Idprivate int id;private List<Integer> scores;
}@Test
public void queryTest() {// 构建查询条件Query query = new Query();Criteria criteria = Criteria.where("scores").elemMatch(Criteria.where("$gte").is(80).and("$lt").is(85));query.addCriteria(criteria);// 执行查询List<Student> student = mongoTemplate.find(query, Student.class, "student");student.forEach(System.out::println);//Student(id=1, scores=[82, 85, 88])
}
2.2 基本类型数组字段

构造测试数据:

db.user.drop()db.user.insertMany([{ name: "Alice", age: 25, email: "alice@example.com", hobbies: ["reading", "writing", "music"] },{ name: "John", age: 30, email: "John@qq.com", hobbies: ["reading", "gaming", "traveling"] },{ name: "Jane", age: 25, email: "Jane@qq.com", hobbies: ["sports", "music", "cooking"] },{ name: "Mike", age: 35, email: "Mike@qq.com", hobbies: ["reading", "writing", "painting"] }
]) 

查询age>=30 并且 hobbies 数组中包含 reading 的文档:

db.student.find({ age: { $gte: 30 }, hobbies: { $elemMatch: { $eq: "reading" } }
})
// 1
{"_id": ObjectId("66a4ab82f074c9a04808d562"),"name": "John","age": 30,"email": "John@qq.com","hobbies": ["reading","gaming","traveling"]
}// 2
{"_id": ObjectId("66a4ab82f074c9a04808d564"),"name": "Mike","age": 35,"email": "Mike@qq.com","hobbies": ["reading","writing","painting"]
}
@Data
@Document(collection = "user")
public class User {@Idprivate String id;private String name;private Integer age;private String email;private List<String> hobbies;public User(String name,Integer age,String email,List<String> hobbies){this.name = name;this.age = age;this.email = email;this.hobbies = hobbies;}
}@Test
public void queryTest() {// 构建查询条件Query query = new Query();Criteria criteria = Criteria.where("age").gte(30).and("hobbies").elemMatch(Criteria.where("$eq").is("reading"));query.addCriteria(criteria);// 执行查询List<User> userList = mongoTemplate.find(query, User.class, "user");userList.forEach(System.out::println);//User(id=66a4ab82f074c9a04808d562, name=John, age=30, email=John@qq.com, hobbies=[reading, gaming, traveling])//User(id=66a4ab82f074c9a04808d564, name=Mike, age=35, email=Mike@qq.com, hobbies=[reading, writing, painting])
}
2.3 嵌入式文档数组字段

构造测试数据:

db.survey.drop()db.survey.insertMany( [{ "_id": 1, "results": [ { "product": "abc", "score": 10 },{ "product": "xyz", "score": 5 } ] },{ "_id": 2, "results": [ { "product": "abc", "score": 8 },{ "product": "xyz", "score": 7 } ] },{ "_id": 3, "results": [ { "product": "abc", "score": 7 },{ "product": "xyz", "score": 8 } ] },{ "_id": 4, "results": [ { "product": "abc", "score": 7 },{ "product": "def", "score": 8 } ] },{ "_id": 5, "results": { "product": "xyz", "score": 9 } }
] )

查询 results 数组中 product=“def” 的文档:

db.survey.find({ results: { $elemMatch: { product: "def" } }
})db.survey.find({ "results.product": "def" }
)
// 1
{"_id": 4,"results": [{"product": "abc","score": 7},{"product": "def","score": 8}]
}
@Data
@Document(collection = "survey")
public class Survey {@Idprivate int id;private List<Result> results;@Datapublic class Result {private String item;private int score;}
}@Test
public void queryTest() {// 构建查询条件Query query = new Query();Criteria criteria = Criteria.where("results").elemMatch(Criteria.where("product").is("def"));query.addCriteria(criteria);// 执行查询List<Survey> surveys = mongoTemplate.find(query, Survey.class);surveys.forEach(System.out::println);//Survey(id=4, results=[Survey.Result(item=null, score=7), Survey.Result(item=null, score=8)])
}
2.4 嵌入式文档数组字段

查询 results 数组中 product=xyz,score>=8 的文档:

db.survey.find({ results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } }
})
// 1
{"_id": 3,"results": [{"product": "abc","score": 7},{"product": "xyz","score": 8}]
}
@Test
public void queryTest() {// 构建查询条件Query query = new Query();Criteria criteria = Criteria.where("results").elemMatch(Criteria.where("product").is("xyz").and("score").gte(8));query.addCriteria(criteria);// 执行查询List<Survey> surveys = mongoTemplate.find(query, Survey.class);surveys.forEach(System.out::println);//Survey(id=3, results=[Survey.Result(item=null, score=7), Survey.Result(item=null, score=8)])
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/876543.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C++画蜡烛图

GPT-4o (OpenAI) 在 C 中绘制蜡烛图通常不像在高级语言&#xff08;如 Python&#xff09;中那么简单&#xff0c;因为 C 并没有内置的图形绘制库。然而&#xff0c;您可以使用一些第三方库来完成这项任务&#xff0c;比如使用 Qt 或者 SFML 等图形库。这里我们以 Qt 库为例&a…

PM2 快速上手指南

PM2是 Node.js 的优秀运行时管理工具&#xff0c;专为简化和优化 Node.js 应用程序的生产部署与运行而设计。 PM2 官网链接: https://pm2.keymetrics.io/ 1.PM2 的优势 持续运行&#xff1a;即使应用出错或崩溃&#xff0c;也能自动重启。负载均衡&#xff1a;智能地自动分…

Vue常用的指令都有哪些?都有什么作用?什么是自定义指令?

常用指令&#xff1a; 1、v-model 多用于表单元素实现双向数据绑定 (同angular中的ng-model) 2、v-for格式&#xff1a; v-for"字段名in(of)数组json"循环数组或json(同angular中的ng repeat),需要注意从vue2开始取消了$index 3、v-show 4、v-hide 隐藏内容 (同a…

Linux shell编程学习笔记67: tracepath命令 追踪数据包的路由信息

0 前言 网络信息是电脑网络信息安全检查中的一块重要内容&#xff0c;Linux和基于Linux的操作系统&#xff0c;提供了很多的网络命令&#xff0c;今天我们研究tracepath命令。 Tracepath 在大多数 Linux 发行版中都是可用的。如果在你的系统中没有预装&#xff0c;请根据你的…

小练习-将阿拉伯数字转换为罗马数字

键盘输入一个字符串&#xff1a; 1.长度小于等于九 2.只能是数字&#xff0c;将内容转换为罗马数字&#xff08;0转换为"") package example;import java.util.Scanner;public class demo04 {public static void main(String[] args) {//录入字符串Scanner sc ne…

SVM(支持向量机)的基本原理

SVM&#xff08;支持向量机&#xff09;的基本原理 支持向量机&#xff08;Support Vector Machine, SVM&#xff09;是一种监督学习算法&#xff0c;主要用于分类和回归任务。其核心思想是在高维空间中寻找一个最优超平面&#xff0c;以最大化不同类别数据点之间的间隔。在二…

Java核心 - Java中的注释详解及最佳实践

作者&#xff1a;逍遥Sean 简介&#xff1a;一个主修Java的Web网站\游戏服务器后端开发者 主页&#xff1a;https://blog.csdn.net/Ureliable 觉得博主文章不错的话&#xff0c;可以三连支持一下~ 如有疑问和建议&#xff0c;请私信或评论留言&#xff01; 前言&#xff1a; 在…

WordPress插件介绍页源码单页Html

源码介绍 WordPress插件介绍页源码单页Html源码&#xff0c;这是一款产品介绍使用页面&#xff0c;也可以用来做其他软件或者应用介绍下载页&#xff0c;界面简约美观&#xff0c;源码由HTMLCSSJS组成&#xff0c;双击html文件可以本地运行效果&#xff0c;也可以上传到服务器…

合作伙伴中心Partner Center中添加了Copilot预览版

目录 一、引言 二、Copilot 功能概述 2.1 Copilot 简介 2.2 Copilot 的核心功能 2.3 Copilot 的访问和使用 三、Copilot 的使用方法 3.1 Copilot 功能区域 3.2 Copilot 使用示例 3.2.1 编写有效提示 3.2.2 使用反馈循环 四、负责任的人工智能 4.1 Copilot 结果的可…

UE4如何直接调试Game

某些功能在编辑器里不好调试&#xff0c;例如Pak&#xff0c;就需要直接调试 Game&#xff0c;做法是选择 Game&#xff0c;不要选择Client&#xff0c;加断点&#xff0c;然后点击 Debug 就好了。 断点调试成功&#xff1a; 同时看到界面&#xff1a;

PCIe总线-Linux内核PCIe软件框架分析(十一)

1.简介 Linux内核PCIe软件框架如下图所示&#xff0c;按照PCIe的模式&#xff0c;可分为RC和EP软件框架。RC的软件框架分为五层&#xff0c;第一层为RC Controller Driver&#xff0c;和RC Controller硬件直接交互&#xff0c;不同的RC Controller&#xff0c;其驱动实现也不相…

【React】详解 React Hooks 使用规则

文章目录 一、Hooks 的基本原则1. 只在最顶层调用 Hooks2. 只在 React 函数组件和自定义 Hooks 中调用 Hooks 二、常见 Hooks 及其使用规则1. useState2. useEffect3. useContext4. useReducer5. useMemo6. useCallback 三、常见错误及其解决方案1. 在条件语句中调用 Hooks2. 在…

RK3568 Linux 平台开发系列讲解(内核入门篇):从内核的角度看外设芯片的驱动

在嵌入式 Linux 开发中,外设芯片的驱动是实现操作系统与硬件之间交互的关键环节。对于 RK3568 这样的处理器平台,理解如何从内核的角度构建和管理外设芯片的驱动程序至关重要。 1. 外设驱动的基础概念 外设驱动(Device Driver)是操作系统与硬件设备之间的桥梁。它负责控…

追问试面试系列:类加载

hi 欢迎来到追问试面试系列:类加载专栏,关于类加载在面试中出现的频率非常高,况且作为一个java开发者也是很有必要掌握的,所以,咱们开始吧。 先来看面试题 面试官:我们可以自己定义一个String类吗?面试官:那你说说这个类的加载过程面试官:说一下这个加载面试官:如何…

nng协议nni_taskq_sys_init(void) 对nni_taskq_systq 初始化

函数调用关系&#xff1a;nni_init(void) --> nni_plat_init(nni_init_helper) 今天分析的函数位于 nni_init_helper()函数中的 nni_taskq_sys_init() 。 这个函数主要用于针对 全局变量 nni_taskq_systq 进行申请空间并初始化。 1. 确定线程数量 num_thr 这个通过宏…

npm 命令的简写,以及-d、-g、-s后缀的区别,和packages.json文件中dependencies和devDependencies的区别

​ 一、npm命令的简写 npm install 等价于 npm inpm install XXX --save 等价于 npm i XXX -S 等价于 npm i XXX -snpm install XXX --save-dev 等价于 npm i XXX -D 等价于 npm i XXX -dnpm install XXX --global 等价于 …

机器学习(二十一):错误分析、创造数据和迁移学习

一、错误分析 假设交叉验证集一共有500个数据点&#xff0c;模型拟合结果中&#xff0c;有100个数据点有误。 错误分析就是&#xff0c;手动地分析这100个错误数据&#xff08;或随机选择一些错误数据&#xff09;&#xff0c;根据它们的共同属性、共同特征分类&#xff0c;然…

在QT中使用多线程并发服务器(C++)

什么是多线程并发服务器&#xff1f;在QT里如何使用多线程并发服务器呢&#xff1f; 多线程并发服务器是一种网络服务器设计&#xff0c;它能够同时处理多个客户端的请求。在多线程服务器中&#xff0c;主线程负责监听和接受来自客户端的连接请求&#xff0c;每当有一个新的连…

C++(week13): C++基础: 标准模板库 STL

文章目录 零、标准模板库 STL一、容器 (Container)1.序列式容器(1)vector2.五种遍历10.vector的迭代器失效问题 (2)deque(3)list 2.关联式容器(1)set4.set的查找(2)find() 8.set中存储自定义类型&#xff1a;三种方法 (2)multiset7.multiset的特殊操作&#xff1a;bound系列函数…

【前端 15】Vue生命周期

Vue生命周期 在Vue.js中&#xff0c;了解组件的生命周期对于开发者来说是至关重要的。Vue的生命周期指的是Vue实例从创建到销毁的一系列过程&#xff0c;每个阶段都对应着特定的生命周期钩子&#xff08;或称为生命周期方法&#xff09;&#xff0c;允许我们在不同的时间点加入…