考虑下面的帖子集合:
{
_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个喜欢评论我想只有在“意见”数组来检索此评论。如果我这样做:
db.posts.find({}, {comments: { $elemMatch: {likes: 4}}})
...我得到这个(这是我想要什么):
{
_id: 1,
comments: [
{
title: "CommentTitle2",
likes: 4
}
]
}
{
_id: 2,
comments: [
{
title: "CommentTitle4",
likes: 4
}
]
}
{
_id: 3
}
但我怎么能检索文档的其余字段,而不必每次申报他们像下面?如果这样,增加了更多的领域后的文件,我也不会改变查找查询
db.posts.find({}, {title: 1, category: 1, comments: { $elemMatch: {likes: 4}}})
感谢
嗨尼尔。感谢您的回答。我认为我的解释不清楚。我想检索所有帖子,以及那些有4个评论的评论,我只想在comment数组下面检索该评论。所以我认为这个预测是必要的。 – rasco22862
@ rasco22862清除声明正是你想要的。 –
再次感谢。有没有办法做到这一点没有明确设置每个领域(标题:1,类别:1等)?因此,如果我向帖子文档添加了另一个字段,我不必修改查询。 – rasco22862