mongodb - MongoDB从数组返回内部文档
问题描述
我正在尝试从文档中的数组中获取一个元素,并且只获取我不想要整个文档的元素
我尝试了另一种方法,但它们都返回了整个文档
db.dept.find({"section.classes.CRN":"1901"}).limit(100)
db.dept.where("section.classes.CRN").eq("1901").limit(100)
json
{
"_id" : ObjectId("5d70ab0c280d6b8ebb850cc1"),
"name" : "Art Studio",
"abbr" : "ARS",
"section" : [
{
"type" : "Undergraduate Courses",
"classes" : [
{
"CRN" : "193",
"Course" : "ARS100",
"Sec" : "01",
"Title" : "Drawing I",
"Cr" : "3",
"Dates" : "8/26-12/19",
"Days" : "MR",
"Time" : "1230P-0320P",
"Loc" : "SAB 226",
"Instructor" : "Schuck",
"Attributes" : "",
"Avail" : "F"
},
{
"CRN" : "293",
"Course" : "ARS100",
"Sec" : "02",
"Title" : "Drawing I",
"Cr" : "3",
"Dates" : "8/26-12/19",
"Days" : "MR",
"Time" : "0330P-0620P",
"Loc" : "SAB 226",
"Instructor" : "Itty",
"Attributes" : "",
"Avail" : "F"
},
{...
在搜索一组 CRN 值时,我试图得到这个或类似的东西
json
[ {
"CRN" : "193",
"Course" : "ARS100",
"Sec" : "01",
"Title" : "Drawing I",
"Cr" : "3",
"Dates" : "8/26-12/19",
...
"Instructor" : "Schuck",
"Attributes" : "",
"Avail" : "F"
}
]
解决方案
db.dept.find({"section.classes.CRN":"1901"},{"section.classes":1}).limit(100)
它projection
在 mongodb 中调用,您在 find 查询中传递第二个对象以指定您想要的结果字段。
所以根据你的上述情况,如果你想要名字,结果部分你应该传递这样的东西
db.dept.find({"section.classes.CRN":"1901"},{"name":1, "section":1}).limit(100)
推荐阅读
- python - 如何获取日志模块中日志记录的列号?
- flutter - 使用 dart 的非对称 zip 文件加密
- mysql - Symfony + Doctrine:如何找到没有特定多对一值的所有用户?
- c# - 无法访问已释放的上下文实例
- docker - 在不使用 imagePullSecrets 的情况下从 kubernetes 中的私有存储库中提取图像
- python - 用于检查调试符号的 Python
- bash - 如何使用 shell 脚本从两个句子中删除重复的单词?
- python - python.dataScience 是 VS Code 中的“未知配置设置”
- ruby - 有没有不同的方法来调用具有相似符号的变量的方法?
- javascript - 表单 onsubmit 返回 false 并仍然继续提交表单