mongodb - 在投影中使用 $elemMatch 并选择字段
问题描述
我正在尝试仅选择文档中的某些字段,同时还使用 $elemmatch。事实证明,字段选择被忽略了。
给定这样的文件:
{
"author": "Robin Sharma",
"data": [
{
"translation": "en",
"content": "foo",
"unwanted_content": "huyu1",
},
{
"translation": "id",
"content": "bar",
"unwanted_content": "huyu2",
{
],
}
我正在使用find()
这个投影配置:
const projection = {
author: 1,
data: {
$elemMatch: {
translation: "en"
},
},
}
预期的
{
"author": "Robin Sharma",
"data": [
{
"translation": "en",
"content": "foo"
},
],
}
实际的
{
"author": "Robin Sharma",
"data": [
{
"translation": "en",
"content": "foo",
"unwanted_content": "huyu1",
},
],
}
我仍然不确定如何摆脱“unwanted_content”字段。
解决方案
我认为您可以这样做以仅从子文档中获取选定的字段。
db.collection.find({"data.translation": "en"},{author: 1, "data.content": 1, "data.translation": 1})
推荐阅读
- python-3.x - RMQ Pika 线程
- python-3.x - 尝试在 Jupyter Notebook 中读取 csv 文件时出现文件未找到错误
- c# - 有没有办法读取统一资产 MonoBehaviour.txt 文件?
- macros - julia 宏的隐式 __source__ 参数不能在引用块中使用
- android - 为什么在 windows 机器和 mac 上构建 apk 时构建大小不同?离子 4 安卓
- angular - rxjs switchMap 在 Angular Guard 中不起作用?
- sql - 使用 COPY 将 .json 文件导入 PostgreSQL 表
- c++ - 为什么 std::cin 没有从一开始就读取
- javascript - 无需刷新页面且无需 php 从 HTML 表单获取数据到 Microsoft Flow 的方法
- java - 无法处理 ArrayIndexOutOfBoundsException