简体   繁体   中英

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:

[
  "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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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