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;智能地自动分…

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

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

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)是操作系统与硬件设备之间的桥梁。它负责控…

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

一、错误分析 假设交叉验证集一共有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;允许我们在不同的时间点加入…

【网络安全】AWS S3 Bucket配置错误导致敏感信息泄露

未经许可&#xff0c;不得转载。 文章目录 前言技术分析正文 前言 AWS&#xff08;Amazon Web Services&#xff09;是亚马逊公司提供的一个安全的云服务平台&#xff0c;旨在为个人、公司和政府机构提供计算能力、存储解决方案、内容交付和其他功能。作为全球领先的云服务提供…

Autodesk Revit v2025 激解锁版下载及安装教程 (三维建模软件)

前言 Revit是欧特克公司知名的三维建模软件&#xff0c;是建筑业BIM体系中使用最广泛的软件之一&#xff0c;其核心功能是三维建筑模型参数化设计、渲染效果图、算量&#xff0c;土建建模、机电建模、用来帮助工程师在施工前精确模拟阶段。 一、下载地址 下载链接&#xff1…

体育赛事中的AI运用

7月24日&#xff0c;国际奥委会&#xff08;IOC&#xff09;举办了新闻发布会&#xff0c;宣布计划在2024年巴黎奥运会上展示一系列创新的人工智能&#xff08;AI&#xff09;技术。这次会议不仅是对即将到来的奥运赛事的预热&#xff0c;也深入探讨了人工智能在体育领域可能带…

快速重装系统

挑选系统 https://d1506.xy58.net/202002/Js_GhostWin7z_x64_2020T.iso WIN11镜像 安装PE启动U盘安装工具 本地安装

【机器学习】深入理解损失函数(Loss Functions)

&#x1f308;个人主页: 鑫宝Code &#x1f525;热门专栏: 闲话杂谈&#xff5c; 炫酷HTML | JavaScript基础 ​&#x1f4ab;个人格言: "如无必要&#xff0c;勿增实体" 文章目录 深入理解损失函数(Loss Functions)什么是损失函数?常见损失函数类型1. 均方误差…

【C++】set的使用

&#x1f525;个人主页&#xff1a; Forcible Bug Maker &#x1f525;专栏&#xff1a; STL || C 目录 &#x1f308;前言&#x1f308;关于set&#x1f525;容量函数emptysize &#x1f525;Modifiersinserteraseclear &#x1f525;Operationsfindcountlower_bound和upper_…

Lesson 51 A pleasant climate

Lesson 51 A pleasant climate 词汇 Greece n. 希腊 Greek a. 希腊的&#xff0c;希腊语 搭配&#xff1a;Greek gift 不怀好意的礼物 例句&#xff1a;他的电脑是不怀好意的礼物。    His computer is a Greek gift. climate n. 气候 长时间&#xff0c;不容易更改的 we…