Mongodb:直接以root身份获取子文档

时间:2018-05-14 13:38:01

标签: mongodb aggregation-framework

使用投影我得到子文档但是在键下,而不是根目录。

当前查询:

db.collection.find({"userId" : {"$ne" : userId}, "gender":{"$in" : interestedin}}, {"profile" : 1, "_id" : 0})

返回如下:

[{"profile":{"firstName":"Payal",...}},{"profile":{"firstName":"Ravinder",...}}...]

我需要的是:

[{"firstName":"Payal",...},{"firstName":"Ravinder",...}...]

我问这个问题是为了确认存在这样或那样的事情,因为我在这里发现了一些相关内容:https://docs.mongodb.com/manual/reference/operator/aggregation/redact/

但是,它使用聚合框架。

示例文档:

{
    "_id": {
        "$oid": "......."
    },
    "id": ".......",
    "facebookId": "......",
    "email": "......@.....com",
    "gender": "....",
    "interestedIn": [
        "....."
    ],
    "isPrivate": false,
    "profile": {
        "name": {
            "firstName": "....",
            "middleName": "",
            "lastName": "....."
        },
        "picture": "........",
        "dob": 1111138064533,
        "meta": {
            "education": [],
            "interests": [],
            "music": [],
            "movies": [],
            "tvSeries": []
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您可以使用$replaceRoot运算符将嵌套对象提升为根级别,请尝试:

db.collection.aggregate([
    { $match: {"userId" : {"$ne" : userId}, "gender":{"$in" : interestedin}} },
    {
        $replaceRoot: {
            newRoot: "$profile.name"
        }
    }
])

答案 1 :(得分:1)

@mickl的答案正朝着正确的方向发展,但我希望补充他的答案,因为他的语法错误。

使用$replaceRoot将文档提升到最高级别。 仅适用于对象,因此您希望在提升嵌套对象之前使用$unwind提取数组数据:

db.collection.aggregate([
    { $match: {"userId" : {"$ne" : userId}, "gender":{"$in" : interestedin}} },
    { $unwind: "$profile"},
    {
        $replaceRoot: {
            newRoot: "$profile"
        }
    }
])