-2

I'm currently struggling to implement an index to my query. Here is the original query:

*db.getCollection('products').aggregate([
    { $unwind: "$categories" },
    {  $unwind: "$categories"},
    {$group: {"_id": "$_id","title": {$first:"$title"},
            "asin":{$first:"$asin"},
            "categories": { $push: "$categories" }} },
    { $match: { "categories": { $in: ['T-Shirts']}} },
    { "$project":{ "_id": 0, "asin":1, "title":1  }  } ])*

This is my current code for my index:

*var cursor = 
db.products.explain("allPlansExecution").find(categories:{"T-Shirts"},{ categories:1, title:1, asin:1, _id:0,})
while (cursor.hasNext()) {
    print(cursor.next());
}*

When I run the index code I should get nReturned as 8 currently at 0.

Could someone please guide me how to do this? Or can someone tell me what they would add?

1 Answers1

0

There is not a simple way to index the individual values in an array contained inside another array.

It this case, since the values in question are string, you could use a text index, such as:

db.products.createIndex({"$**":"text"})

You could then use the $text query operator to search the index for an exact match:

db.products.find({$text:{$search:"\"T-Shirts\""}},{_id:0, asin:1, title:1})
Joe
  • 25,000
  • 3
  • 22
  • 44