MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Mongodb aggrega tre raccolte

Puoi provare sotto la query di aggregazione.

La query seguente spinge le sections nel department quando sono uniti e $group per spingere il reparto a creare la struttura finale.

db.college.aggregate([
  {
    "$match": {
      "university_id": "5834ecf7432d92675bde9d82"
    }
  },
  {
    "$lookup": {
      "localField": "_id",
      "from": "departments",
      "foreignField": "college_id",
      "as": "departments"
    }
  },
  {
   "$unwind": {
     "path": "$departments",
     "preserveNullAndEmptyArrays": true
    }
  },
  {
    "$lookup": {
      "localField": "departments._id",
      "from": "sections",
      "foreignField": "department_id",
      "as": "departments.sections"
    }
  },
  {
    "$group": {
      "_id": "$_id",
      "name": {
        "$first": "$name"
      },
      "university_id": {
        "$first": "$university_id"
      },
      "departments": {
        "$push": "$departments"
      }
    }
  }
])