MongoDB.live, free & fully virtual. June 9th - 10th. Register Now MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

Aggregation pipeline isn't returning expected results

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?

It looks like your question is actually about your aggregation pipeline not returning the expected results rather than an indexing improvement.

In order for someone to provide suggestions can you please comment with:

  • a sample document that should match this query, but doesn’t
  • the specific version of MongoDB server you are using

Note: your aggregation query as written will not benefit from an index because it is processing all documents in the collection. See Pipeline Operators and Indexes for more information.

Regards,
Stennie