如何在父文档列表中过滤子文档

时间:2019-05-03 22:45:07

标签: javascript mongodb express mongoose

我试图根据子文档字段过滤父文档列表中的子文档数组。使用“ populate()”引用另一个集合中的子文档时,我已经能够做到这一点。但是当子文档直接位于父文档中时,我无法解决

我尝试使用

Parent.find({ workExperiences: { $elemMatch: { isActive: true } } })

但是它会基于子文档匹配项过滤父文档

文件就像

[
    {
        "state": 2,
        "country": 3,
        "zip": "500053 ",
        "workExperiences": [
            {
                "_id": "5ccca2bf2802323e80f21a72",
                "jobTitle": "UI Dev 1",
                "primarySkills": "ANgular",
                "secondarySkills": "Javascript",
                "isActive": true
            },
            {
                "_id": "5ccca2bf2802323e80f21a71",
                "jobTitle": "UI Dev Two",
                "primarySkills": "ANgular",
                "secondarySkills": "Javascript",
                "isActive": true
            }
        ]
    },
    {
        "state": 2,
        "country": 3,
        "zip": "500053 ",
        "workExperiences": [
            {
                "_id": "5ccca2bf2802323e80f21a72",
                "jobTitle": "UI Dev 3",
                "primarySkills": "ANgular",
                "secondarySkills": "Javascript",
                "isActive": false
            },
            {
                "_id": "5ccca2bf2802323e80f21a71",
                "jobTitle": "UI Dev 4",
                "primarySkills": "ANgular",
                "secondarySkills": "Javascript",
                "isActive": true
            }
        ]
    }
]

我可以从中查询


[
    {
        "state": 2,
        "country": 3,
        "zip": "500053 ",
        "workExperiences": [
            {
                "_id": "5ccca2bf2802323e80f21a72",
                "jobTitle": "UI Dev 1",
                "primarySkills": "ANgular",
                "secondarySkills": "Javascript",
                "isActive": true
            },
            {
                "_id": "5ccca2bf2802323e80f21a71",
                "jobTitle": "UI Dev Two",
                "primarySkills": "ANgular",
                "secondarySkills": "Javascript",
                "isActive": true
            }
        ]
    },
    {
        "state": 2,
        "country": 3,
        "zip": "500053 ",
        "workExperiences": [
            {
                "_id": "5ccca2bf2802323e80f21a71",
                "jobTitle": "UI Dev 4",
                "primarySkills": "ANgular",
                "secondarySkills": "Javascript",
                "isActive": true
            }
        ]
    }
]

谢谢

0 个答案:

没有答案