Home > database >  mongodb, query if any element of array within property contain some regex
mongodb, query if any element of array within property contain some regex

Time:06-02

i have a document structured this way

{
_id:'1'
text:'xxxxxxxc'
choices:{
    a:['xxx','yyy','zzz'],
    b:['aaa','bbb','ccc'],
    c:['lll','mmm','ddd'],
    }
}

....and many other document...

{
_id:'2'
text:'xxxxxxxc'
choices:{
    a:['ooo','sss','qqq'],
    b:['iii','hhh','ggg'],
    c:['ddd','eee','fff'],
    }
}

so i cant figure out to search if any of choices key contains an array that contains some string

to be more precise: i want to query entire document and return the document if ANY of the choices keys' array has element that matches the query.

so if i search for 'yyy' , it should simply return document of_id:1 and other docs, that has 'yyy' in array in any of its choices key (be it in a,b,c, these keys can be more than c, that is to z and beyond) ...and not the _id:2 because it has no element 'yyy' in any of its array of its choice

CodePudding user response:

db.collection.aggregate([
  {
    $addFields: {
      "c": {
        "$objectToArray": "$choices"
      }
    }
  },
  {
    $match: {
      "c.v": "yyy"
    }
  },
  {
    "$project": {
      c: 0
    }
  }
])

Reshape and find what you need. Ignore other temp fields created.

Playground

  • Related