1

I need to count records grouped by tags and have filtered bofore including in ones

// in db
{tags: ['video', 'Alex'], ... },
{tags: ['video', 'John'], ... },
{tags: ['video', 'John'], ... },
{tags: ['text', 'Alex'], ... },
{tags: ['text', 'John'], ... },


client.db('mydb').collection('Files').aggregate(
        [
          { $group: { _id: { tags: '$tags' }, total: { $sum: 1 } } },
          { $match: { tags: 'video' } },
        ],
      ).toArray()

But sadly I got zero docs. If remove $group section I got 3 docs. In original request I anticipated 2 docs

{ _id: ['video', 'Alex'], total: 1 },
{ _id: ['video', 'John'], total: 2 }

1 Answer 1

1

In aggregation the order of pipeline is important, as output of previous stage is fed to the next one.

Your query is almost there basis the expected output. Just move $match stage before the $group stage.

Query:

db.collection.aggregate([
  {
    $match: {
      "tags": "video"
    }
  },
  {
    $group: {
      _id: {
        tags: "$tags"
      },
      total: {
        $sum: 1
      }
    }
  }
]);

Working Example

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.