mongodb return 查询字段只是子文档

mongodb return just the subdocument by querying the field

我有这样的结构:

{
"_id" : ObjectId("5b155aa3e7179a6034c6dd5b"),
"pinnedKpi" : {
    "Ver01" : [
        "130",
        "138",
        "122",
        "134"
    ],
    "Ver02" : [
        "265",
        "263",
        "142",
        "264"
    ],
    "Ver03" : [ ],
    "Ver04" : [
        "126",
        "134",
        "122",
        "138"
    ]
},
"email" : "john@doe.ca",

是否可以像 return 那样只查询 email = john@doe.ca 和 pinnedKpi.Ver01 的数组 ---> ["130","138","122","134"]

就用这个:

db.collection.find({ // find all documents
    "email": "john@doe.ca" // where the "email" field equals some value
}, {
    "_id": 0, // do not return the "_id" field (included by default)
    "pinnedKpi.Ver01": 1 // only return the "pinnedKpi.Ver01" field
})

如果数组不需要作为响应的根元素,您可以使用以下查询 return pinnedKpi.Ver01 数组,其中包含电子邮件条件和 pinnedKpi 数组中是否存在 Ver01 元素:

    db.test1.find(
      {"email" : "john@doe.ca", "pinnedKpi.Ver01" : {"$exists" : true}},
    {"pinnedKpi.Ver01" : 1}
    );

哪个输出:

{ 
    "_id" : ObjectId("5b155aa3e7179a6034c6dd5b"), 
    "pinnedKpi" : {
        "Ver01" : [
            "130", 
            "138", 
            "122", 
            "134"
        ]
    }
}

如果数组结果需要作为根元素,可以使用聚合框架来实现:

db.test1.aggregate(
    [
        {
            $match: {email:"john@doe.ca","pinnedKpi.Ver01":{$exists:true}}
        },
        {
            $replaceRoot: {
            newRoot: "$pinnedKpi"
            }
        },
        {
            $project: {
               Ver01:1
            }
        },
    ]
);

输出:

{ 
    "Ver01" : [
        "130", 
        "138", 
        "122", 
        "134"
    ]
}