1

I was trying to fetch distinct tags from array for auto-complete module. The collection format is:

{
  tags:["apple","mango","apple-pie"]
},
{
  tags: ["man","lemon","lemon-lite"]
}

Now, I am interested in getting distinct tags, with prefix q.

The query that I triggered is:

db.portfolio.distinct("tags",{"tags":/app/});

However, this query returned entire array: ["apple","mango","apple-pie"].

My requirement is: ["apple", "apple-pie"].

How can I modify my query to get desired result?

1
  • Were you able to find a solution to the issue you were facing? Commented Mar 1, 2015 at 19:12

2 Answers 2

2

You can do this with aggregation.

  1. You $unwind the tags array.
  2. You $match those tags you are looking for according to the regular expression given.
  3. You $group the tags into a set using $addToSet.

The code looks something like this:

> db.portfolio.aggregate([
    { "$unwind": "$tags" },
    { "$match": { "tags": /app/ }},
    { "$group":
        {
            "_id": null,
            "tags": { "$addToSet": "$tags" }
        }
    }
]);
{ "_id" : null, "tags" : [ "apple-pie", "apple" ] }
Sign up to request clarification or add additional context in comments.

Comments

0

Not possible with distinct because query will return documents containing matching tags(/app/) which mean there will be non matching tags as well. distinct gets a distinct set from all these tags. So you will have to filter the returning array again( using regex /app/)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.