首页 > 解决方案 > 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"
     }
   ]

标签: mongodbmongodb-queryaggregation-frameworkprojection

解决方案


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)

推荐阅读