wazzaday
wazzaday

Reputation: 9664

MongoDB extract subdocument as actual document

I have a document structure like:

{
    _id: '323423423fsdr2',
    title: 'hey',
    location: 'Someplace',
    draft: {
        title: 'hey im a draft',
        location: 'Someplace',
    }
}

How would I query mongo to get only the draft version, but have it returned as if it were the root level document like:

db.collection.find(somequery)

returns

{
    title: 'hey im a draft',
    location: 'Someplace'
}

I am looking into the aggregation framework but I am unsure on how I would even begin. It would be cool if I could avoid extracting the document at the application level.

Upvotes: 2

Views: 215

Answers (1)

profesor79
profesor79

Reputation: 9473

Aggregation is the only choice in this case, use $match to pass your filter see more here

db.collection.aggregate([{
            $project : {
                _id : 0,
                title : "$draft.title",
                location : "$draft.location"
            }
        }
    ])

Upvotes: 2

Related Questions