How can I get all fields when using $ elemMatch?

Consider the following message collection:

{
    _id: 1,
    title: "Title1",
    category: "Category1",
    comments: [
                {
                    title: "CommentTitle1",
                    likes: 3
                },
                {
                    title: "CommentTitle2",
                    likes: 4
                }

            ]
}
{
    _id: 2,
    title: "Title2",
    category: "Category2",
    comments: [
                {
                    title: "CommentTitle3",
                    likes: 1
                },
                {
                    title: "CommentTitle4",
                    likes: 4
                }

            ]

}
{
    _id: 3,
    title: "Title3",
    category: "Category2",
    comments: [
                {
                    title: "CommentTitle5",
                    likes: 1
                },
                {
                    title: "CommentTitle6",
                    likes: 3
                }
        ]
    }

I want to get all the posts, and if one post has a comment with 4 likes, I want to get this comment only under the "comments" array. If I do this:

db.posts.find({}, {comments: { $elemMatch: {likes: 4}}})

... I get this (this is exactly what I want):

{
    _id: 1,
    comments: [
        {
            title: "CommentTitle2",
            likes: 4
        }
    ]
}
{
    _id: 2,
    comments: [
        {
            title: "CommentTitle4",
            likes: 4
        }
    ]
}
{
    _id: 3
} 

But how can I get the remaining document fields without declaring each of them, as shown below? Thus, if more fields were added to the mail document, I would not have to change the search request

db.posts.find({}, {title: 1, category: 1, comments: { $elemMatch: {likes: 4}}})

thank

+3
source share
1 answer

- EDIT -

. , , , . , , :

fooobar.com/questions/2107100/...

. , .

, , .

, , , . , , SQL SELECT. * , , , , _id, , , , i.e {_id: 0}

, , $elemMatch query. .

:

db.posts.find(
    { comments: { $elemMatch: {likes: 4}}},
    { title: 1, category: 1, "comments.likes.$": 1 }
)

, , position $ .

. :

http://docs.mongodb.org/manual/reference/operator/query/elemMatch/

http://docs.mongodb.org/manual/reference/operator/projection/elemMatch/

+1

All Articles