首页 > 解决方案 > 在 MongoDb 中返回没有其键的对象

问题描述

我正在使用 MongoDb 3.2

假设我在 MongoDb 集合中有这个文档:

{
    "_id" : ObjectId("5bad65b9777f6df3ce840fd1"),
    "entryCode" : "1234",
    "first" : {
        "someKey" : "x",
        "anotherKey" : "y"
    },
    "second" : {
        "someKey" : "u",
        "anotherKey" : "v",
    }
}

当我执行以下查询时: db.collection.find({entryCode:"1234"},{_id:0, first:1})

我得到这个返回的结果:

{
    "first" : {
        "someKey" : "x",
        "anotherKey" : "y"
    }
}

但是,我想返回的是:

{
    "someKey" : "x",
    "anotherKey" : "y"
}

请注意,我希望键first成为返回值的一部分。只是里面的对象值。我可以使用什么 Mongo 查询?

标签: mongodbmongodb-query

解决方案


您需要$replaceRoot运算符,请尝试:

db.col.aggregate([
    {   $match: { entryCode:"1234" } },
    {
        $replaceRoot: {
            newRoot: "$first"
        }
    }
])

编辑:在 MongoDB 3.2 中,您只能$project明确使用和指定字段:

db.col.aggregate([
    {   $match: { entryCode:"1234" } },
    {
        $project: {
            _id: 0,
            someKey: "$first.someKey",
            anotherKey: "$first.anotherKey",
        }
    }
])

推荐阅读