mongodb通过查询字段仅返回子文档

时间:2018-07-05 17:46:47

标签: mongodb mongoose nested subdocument

我有这样的结构:

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

是否可以进行查询,例如仅返回其中email = john@doe.ca和pinnedKpi.Ver01 ---> ["130","138","122","134"]

的数组

2 个答案:

答案 0 :(得分:1)

只需使用此:

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
})

答案 1 :(得分:0)

如果数组不必是响应的根元素,则可以使用以下查询返回具有电子邮件条件和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"
    ]
}