mongodb嵌套查询子集合,如何过滤掉不符合条件的子集数据
时间: 2023-08-31 19:27:14
浏览: 115
### 回答1:
在 MongoDB 中,可以使用 $elemMatch 运算符来过滤嵌套在数组中的[[文档](https://geek.csdn.net/educolumn/3ff36b49b1643d1100a457ee835cde75?spm=1055.2569.3001.10083)](https://geek.csdn.net/edu/300981ef51993cfd737d329c71ba77f9?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083),具体用法如下:
例如,假设有一个[集合](https://geek.csdn.net/educolumn/ba94496e6cfa8630df5d047358ad9719?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083) `students`,其中包含的[[文档](https://geek.csdn.net/educolumn/3ff36b49b1643d1100a457ee835cde75?spm=1055.2569.3001.10083)](https://geek.csdn.net/edu/300981ef51993cfd737d329c71ba77f9?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083)如下:
"_id": 1,
"name": "张三",
"scores": [
{ "subject": "数学", "score": 80 },
{ "subject": "语文", "score": 90 },
{ "subject": "英语", "score": 70 }
"_id": 2,
"name": "李四",
"scores": [
{ "subject": "数学", "score": 60 },
{ "subject": "语文", "score": 80 },
{ "subject": "英语", "score": 90 }
"_id": 3,
"name": "王五",
"scores": [
{ "subject": "数学", "score": 90 },
{ "subject": "语文", "score": 60 },
{ "subject": "英语", "score": 80 }
```