1

What I have

I have a DB in MongoDB like this:

{
    "_id": {
        "$oid": "60ba531acbfed3545c51a49e"
    },
    "email": "[email protected]",
    "Formats": [{
        "format": "AST-QC",
    }],
    "Series": [{
        "seq": "AST-QC - 1",
     },
     {
        "seq": "AST-QC - 2",
     },
     {
        "seq": "AST-QD - 1",
     }]
}

I am successfully getting the data from the Formats array using this query:

const pipeline =  [
    { $match: { "email": email } },
    { $unwind: "$Formats" },    
]
const res = await colc.aggregate(pipeline)

What I want

Along with the data in the Formats array, I need the count of every format that is used by seq in Series array.

I am certain that it can be done using $addFields, Something like this.

const pipeline =  [
    { $match: { "email": email } },
    { $unwind: "$Formats" },
    { $addFields: {"Formats.count": 0} }
]
const res = await colc.aggregate(pipeline)

But I am not sure as to how.

I don't want to call another query using .count()

2
  • what count you need? AST-QC - 1 concated number or matching string? Commented Jun 14, 2021 at 15:32
  • just the matching string from format, i.e. AST-QC not the concated number. Commented Jun 14, 2021 at 15:34

1 Answer 1

1
  • $filter to iterate loop of Series array
  • $regexMatch to search format in seb
  • $size to get total elements in filtered result
const pipeline = [
  { $match: { email: email } },
  { $unwind: "$Formats" },
  {
    $addFields: {
      "Formats.count": {
        $size: {
          $filter: {
            input: "$Series",
            cond: {
              $regexMatch: {
                input: "$$this.seq",
                regex: "$Formats.format"
              }
            }
          }
        }
      }
    }
  }
]

Playground

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

Comments

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.