Home > Back-end >  Mongodb 2 collections aggregation
Mongodb 2 collections aggregation

Time:11-21

Summarize points in second collection and put it in the first collection

given two collections:

a:

    {
     _id: 123323525245,
     token: "token_1",
     points: 0
    },
    {
     _id: 3454545334
     token: "token_2"
     points: 0
    }

b:

    _id: 1324454:
    lines: [
    {
      token: "token_1",
      points: 20
    },
    {
      token: "token_1",
      points: 10
    },
    {
      token: "token_2",
      points: 12
    }
  ]

I want to summarize all the points in collection b by token, and put it in a collection expected a collection:

a:
    {
       _id: 123323525245,
       token: "token_1",
       points: 30
    },
    {
       _id: 3454545334
       token: "token_2"
       points: 12
    }

What query should I use?

CodePudding user response:

Unwind collection b first, and then group by token.

db.b.aggregate([
  {
    "$unwind": "$lines"
  },
  {
    "$group": {
      "_id": "$lines.token",
      "points": {
        "$sum": "$lines.points"
      }
    }
  },
  {
    "$lookup": {
      "from": "a",
      "localField": "_id",
      "foreignField": "token",
      "as": "docs"
    }
  },
  {
    "$project": {
      "_id": {
        "$first": "$docs._id"
      },
      "points": "$points",
      "token": "$_id"
    }
  }
])

mongoplayground

  • Related