Search code examples
djangomongodbpymongo

Nested Array search in MongoDB/PyMongo while using aggregate


I am trying to search for a keyword inside array of arrays in a Mongo document.

{
  "PRODUCT_NAME" : "Truffle Cake",

  "TAGS": [
            ["Cakes", 100],
            ["Flowers", 100],
       ]
}

Usually, I would do something like this and it would work.

db.collection.find( {"TAGS":{"$elemMatch":{ "$elemMatch": {"$in":['search_text']} } }} )

But now, I changed this query to an aggregate based query due to other requirements. I've tried $filter , $match but not able to replicate the above query exactly..

Can anyone convert the above code so that it can directly work with aggregate? (I use PyMongo)


Solution

  • $match uses the same query syntax as the query language (find), from the docs:

    The query syntax is identical to the read operation query syntax;

    This means if you have a query that works in a "find", it will also work within a $match stage, like so:

    db.collection.aggregate([
      {
        $match: {
          "TAGS": {
            "$elemMatch": {
              "$elemMatch": {
                "$in": [
                  "Cakes"
                ]
              }
            }
          }
        }
      }
    ])
    

    Check this live on Mongo Playground