Kingsley CA
Kingsley CA

Reputation: 11634

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

Upvotes: 0

Views: 36

Answers (1)

RaR
RaR

Reputation: 3223

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!

Upvotes: 2

Related Questions