【发布时间】:2014-03-02 12:57:49
【问题描述】:
考虑以下帖子集合:
{
_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
}
]
}
我想检索所有帖子,如果一个帖子有 4 个赞的评论,我想仅在“cmets”数组下检索该评论。如果我这样做:
db.posts.find({}, {comments: { $elemMatch: {likes: 4}}})
...我明白了(这正是我想要的):
{
_id: 1,
comments: [
{
title: "CommentTitle2",
likes: 4
}
]
}
{
_id: 2,
comments: [
{
title: "CommentTitle4",
likes: 4
}
]
}
{
_id: 3
}
但是我怎样才能检索文档的其余字段而不必像下面这样声明每个字段?这样,如果在 post 文档中添加更多字段,我就不必更改查找查询
db.posts.find({}, {title: 1, category: 1, comments: { $elemMatch: {likes: 4}}})
谢谢
【问题讨论】:
标签: mongodb mongoose mongodb-query