我在mongo db中有一个称为页面的集合。在这种情况下,我有一系列称为文章的文档。在该数组中的每个文档中,我都说了文章编号和文章内容。
我想做的是放开文章,然后使用$ text在文章Content中搜索单词。但是$ text必须处于开发的第一阶段。
如果我在流水线的第一阶段执行但不放松,现在会发生的情况是,在第一次搜索文本时,它将返回该文档的所有剩余文章,而不管它是否包含文本。
注意:Pages集合包含很多文档。
样品采集 :
{
pageNo: 1,
articles:[{
articleNo:1,
articleContent:"cat dog cat dog"
},{
articleNo:2,
articleContent:" Some random text"
}]
},
{
pageNo: 2,
articles:[{
articleNo:1,
articleContent:"Some random text"
},{
articleNo:2,
articleContent:"cat dog cat"
}]
}
预期的输出:说我搜索“猫”
{
pageNo:1,
articles:[{
articleNo:1,
articleContent:"cat dog cat dog"
}]
},
{
pageNo:2,
articles:[{
articleNo:2,
articleContent:"cat dog cat"
}]
}
以下答案将返回您想要的结果。第一个$match
仅cat
在text
索引的帮助下仅用于过滤文档,而根本不过滤文档。如果您不使用此阶段,则结果将相同且正确,但可能会更慢。
db.pages.aggregate([
{
$match: {
$text: {
$search: "cat"
}
}
},
{
$unwind: '$articles'
},
{
$match: {
'articles.articleContent': /cat/
}
},
{
$group: {
_id: {
_id: '$_id',
pageNo: '$pageNo'
},
articles: {
$push: '$articles'
}
}
},
{
$project: {
_id: '$_id._id',
pageNo: '$_id.pageNo',
articles: 1
}
}
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句