Return object without its key in MongoDb

Viewed 828

I am using MongoDb 3.2

Say I have this document in a MongoDb collection:

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

When I execute the following query: db.collection.find({entryCode:"1234"},{_id:0, first:1})

I get this returned result:

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

However, what I'd like to return is this:

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

Notice I do not want the key first to be a part of the returned value. Just the object value within. What Mongo query can I use?

1 Answers

You need $replaceRoot operator, try:

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

EDIT: In MongoDB 3.2 you can only use $project and specify fields explicitly:

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