0

I'm need to group a mongo collection and aggregate.

Example Collection

[{id:"1", skill: "cooking"},{id:"1", skill: "fishing"}]

Lookup Collection

[{ name: "cooking", value: 3 }, { name: "fishing", value: 2 }]

Desired Result

[{id: "1", skills: [{ value: 3, "cooking" }, { value: 2, "fishing"}]}]

Here's how far I am.

db.talent.aggregate([
    { 
        $group: '$id' 
        skills: { $addToSet: '$skill' }
    },
])

Result:

[{id: "1", skills: ["cooking", "fishing"]}]

I'm wondering if this is even possible.

I miss SQL, need help!

1 Answer 1

1

We can do this using $lookup, $group and $project in the aggregation pipeline

Shown below is the mongodb shell query

db.example_collection.aggregate([
  {
    $lookup: {
      from: "lookup_collection",
      localField: "skill",
      foreignField: "name",
      as: "skills"
    }
  },
  {
    $group: {
      _id: "$id",
      skills: {
        $push: "$skills"
      }
    }
  },
  {
    $project: {
      "id": "$_id",
      "skills.name": 1,
      "skills.value": 1,
      "_id": 0
    }
  }
])
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.