can aggregation give me a document with a count of sub-documents, based on criteria of sub-doc?

6 views
Skip to first unread message

Derick Bailey

unread,
Jun 17, 2015, 2:06:09 PM6/17/15
to mongoo...@googlegroups.com
I have a complex data structure where a "schedule" contains "jobs". Right now, I'm doing a lot of "forEach" loops in my code to find all of the jobs that are in a specific state (have a "status" field of whatever value). This works fine, but is tremendously slow, with hundreds of jobs and dozens of schedules listed in a search result screen.

Is it possible to use the mongodb / mongoose aggregation pipeline to get the results that I want?

for example, I want to go from a structure like this:

{
  _id: "(object id)",
  name: "something",
  jobs: [
    {
      _id: "(object id)",
      name: "j1",
      status: 0,
      statusName: "unresolved"
    },
    {
      _id: "(object id)",
      name: "j2",
      status: 0,
      statusName: "unresolved"
    },
    {
      _id: "(object id)",
      name: "j3",
      status: 1,
      statusName: "resolved"
    }
  ]
}

and have this return a data structure that looks something like this (thought the actual resulting structure can vary at this point)

{
  _id: "(object id")
  name: "something",
  jobs: {
    unresolved: 2,
    resolved: 1
  }
}

is this possible? I'm not super picky about what the final data structure looks like... i just want to have mongodb do the work of aggregating and counting the jobs by status, instead of me doing it in code.

thanks,

  - Derick
Reply all
Reply to author
Forward
0 new messages