MongoDB lookup when foreign field is an array of objects

后端 未结 1 856
盖世英雄少女心
盖世英雄少女心 2020-12-02 02:28

I have two collections initiatives and resources:

initiative document example:

{
    \"_id\" : ObjectId(\         


        
相关标签:
1条回答
  • 2020-12-02 02:57

    You can use below aggregation with mongodb 3.6 and above

    db.resources.aggregate([
      { "$match": { "type": "FUNC" } },
      { "$lookup": {
        "from": "initiatives",
        "let": { "id": "$_id" },
        "pipeline": [
          { "$match": { "$expr": { "$in": ["$$id", "$ressources.function"] } } },
          { "$unwind": "$ressources" },
          { "$match": { "$expr": { "$eq": ["$ressources.function", "$$id"] } } },
          { "$group": {
            "_id": "$ressources.function",
            "participation_sum": { "$sum": "$ressources.participating" }
          }}
        ],
        "as": "result"
      }}
    ])
    
    0 讨论(0)
提交回复
热议问题