返回 mongodb 中的数组

Returning an array in mongodb

我正在尝试 return 下面文档中数组的某些元素。

{
"_id": 2,
"awardAmount": 6000,
"url": "www.url.com",
"numAwards": 3,
"award": "Faculty Seed Research Grant",
"Type": "faculty",
"Applicates": [
    {
        "School": "psu",
        "Name": "tom",
        "URL": "www.url.com",
        "Time": "",
        "Research": "",
        "Budge": 7500,
        "appId": 100,
        "citizenship": "us",
        "Major": "mat",
        "preAwards": "None",
        "Advisor": ""
    },
    {
        "School": "ffff",
        "Name": "KEVIN",
        "URL": "www.url.com",
        "Time": "5/5/5-6/6/6",
        "Research": "topology",
        "Budge": 9850,
        "appId": 101,
        "citizenship": "us",
        "Major": "gym",
        "preAwards": "None",
        "Advisor": "Dr. cool",
        "Evaluators": [
            {
                "abstractScore": 3,
                "goalsObjectivesScore": 4,
                "evalNum": 1
            },
            {
                "abstractScore": 545646,
                "goalsObjectivesScore": 46546,
                "evalNum": 2
            }
        ]
    }
]
}

我只想要 "Applicates" 数据,如果它们有 "Evaluators" 字段。这是我正在尝试的

db.coll.find({'Applicates.Evaluators':{'$exists': True }})

这给了我整个文档,但我只想要 "Applicates" 数据,其中包含 "Evaluators" 字段,就像这样。

{
"_id": 2,
"awardAmount": 6000,
"url": "www.url.com",
"numAwards": 3,
"award": "Faculty Seed Research Grant",
"Type": "faculty",
"Applicates": [
    {
        "School": "ffff",
        "Name": "KEVIN",
        "URL": "www.url.com",
        "Time": "5/5/5-6/6/6",
        "Research": "topology",
        "Budge": 9850,
        "appId": 101,
        "citizenship": "us",
        "Major": "gym",
        "preAwards": "None",
        "Advisor": "Dr. cool",
        "Evaluators": [
            {
                "abstractScore": 3,
                "goalsObjectivesScore": 4,
                "evalNum": 1
            },
            {
                "abstractScore": 545646,
                "goalsObjectivesScore": 46546,
                "evalNum": 2
            }
        ]
    }
]
}

试试这个(关键是使用 $unwind 运算符)

db.coll.aggregate(
[
{ $match : {'Applicates.Evaluators':{'$exists': true }} },
{ $unwind : "$Applicates" },
{ $match : {'Applicates.Evaluators':{'$exists': true }} },
{ $group : { _id : "$_id", 
    'Applicates' : {$push : '$Applicates'} , 
    awardAmount : {$first : '$awardAmount'},
    url : {$first : '$url'},
    award : {$first : '$award'},
    numAwards : {$first : '$numAwards'},
    award : {$first : '$award'},
    Type : {$first : '$Type'},
    }},
])