0

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)

1 Answer 1

1

$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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much, can't believe I missed that!
Very similar question, I believe you could help with that as well - stackoverflow.com/questions/72727058/…
sure, answered:)

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.