$unwind 和 $text 在聚合框架 mongodb 中的使用 [英] Use of $unwind and $text in aggregation framework mongodb

查看:18
本文介绍了$unwind 和 $text 在聚合框架 mongodb 中的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 mongo db 中有一个名为 pages 的集合.因为我有一组称为文章的文档.在该数组中的每个文档中,我都提到了文章编号和文章内容.

I have a collection in mongo db say called pages. In that i have an array of documents called articles. And in each of those documents in that array i have say an article number and article content.

我想要做的是展开文章,然后使用 $text 在文章内容中搜索单词.但是 $text 必须处于管道的第一阶段.

What i want to do is that unwind the articles and then use $text to search for a word in article Content. But $text has to be in first stage of pipeline.

如果我在没有展开的管道的第一阶段执行现在会发生什么是在第一次搜索文本时它返回该文档的所有剩余文章,而不管它是否有文本.

What happens now if i execute in first stage of pipeline without unwinding is that on first search of text it returns all the remaining articles for that document irrespective of whether it has the text.

注意:Pages 集合包含大量文档.

Note : Pages collection contains a lot of documents.

样本集:

{
   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"
        }]
}

预期输出:假设我搜索cat"

Expected output: Say i search for "cat"

{
   pageNo:1,
    articles:[{
          articleNo:1,
          articleContent:"cat dog cat dog"
        }]
},
{
  pageNo:2,
   articles:[{
          articleNo:2,
          articleContent:"cat dog cat" 
        }]
}

推荐答案

以下答案将返回您想要的结果.第一个 $match 仅用于在 text 索引的帮助下过滤没有 cat 的文档.如果不使用此阶段,结果将相同且正确,但可能会更慢.

The below answer will return your desired results. the first $match is used only to filter documents without cat in it at all, with the help of the text index. If you don't use this stage, the results will be the same and correct but may be slower.

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
         }
     }
])

这篇关于$unwind 和 $text 在聚合框架 mongodb 中的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆