简体   繁体   English

MongoDB-查找并返回每个文档中数组的所有项目

[英]MongoDB - Find and return all the items of an array in each document

so I have this system where users can input tags, but i want to add suggestions/auto-complete with dynamic data from all the previous tags in the database. 所以我有一个用户可以在其中输入标签的系统,但是我想添加来自数据库中所有先前标签的动态数据的建议/自动完成功能。

Here's what the data looks like: 数据如下所示:

    collection = [
      {
        title: "Avengers",
        tags:["si-fi", "powers", "super-heroes", "iron-man"],
        ...
      },
      {
        title: "Lego Movie"
        tags:["spider-man", "bottle", "man of steel"],
        ...
      }
      ...
    ]

So I want to retreive an array of all the tags that match a search string. 因此,我想检索所有与搜索字符串匹配的标签的数组。

For example, if I search with 'man' , I want the data returned to be: 例如,如果我搜索'man' ,我希望返回的数据为:

[
  "iron-man",
  "spider-man",
  "man of steel"
]

I think it cannot be done by direct querying. 我认为无法通过直接查询来完成。 The following aggregation can do, 以下聚合可以做到,

    db.collection.aggregate([{
        $unwind: '$tags'
    }, {
        $match: {
            'tags': { $regex: 'man' }
        }
    }, {
        $group: {
            _id: null,
            tags: { '$addToSet': '$tags' }
        }
    }]);

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM