MongoDB Collection별 검색 결과 합치기

2020. 4. 20. 22:36서버 프로그래밍

두개의 컬랙션을 Join하는 것이 아니라, 각각 컬랙션별로 검색한 결과를 최종적으로 합치는 방법은 다음과 같다.

// Create employees data for testing the union.
db.getCollection('employees').insert({ name: "John", type: "employee", department: "sales" });
db.getCollection('employees').insert({ name: "Martha", type: "employee", department: "accounting" });
db.getCollection('employees').insert({ name: "Amy", type: "employee", department: "warehouse" });
db.getCollection('employees').insert({ name: "Mike", type: "employee", department: "warehouse"  });

// Create freelancers data for testing the union.
db.getCollection('freelancers').insert({ name: "Stephany", type: "freelancer", department: "accounting" });
db.getCollection('freelancers').insert({ name: "Martin", type: "freelancer", department: "sales" });
db.getCollection('freelancers').insert({ name: "Doug", type: "freelancer", department: "warehouse"  });
db.getCollection('freelancers').insert({ name: "Brenda", type: "freelancer", department: "sales"  });

// Here we do a union of the employees and freelancers using a single aggregation query.
db.getCollection('freelancers').aggregate( // 1. Use any collection containing at least one document.
  [
    { $limit: 1 }, // 2. Keep only one document of the collection.
    { $project: { _id: '$$REMOVE' } }, // 3. Remove everything from the document.

    // 4. Lookup collections to union together.
    { $lookup: { from: 'employees', pipeline: [{ $match: { department: 'sales' } }], as: 'employees' } },
    { $lookup: { from: 'freelancers', pipeline: [{ $match: { department: 'sales' } }], as: 'freelancers' } },

    // 5. Union the collections together with a projection.
    { $project: { union: { $concatArrays: ["$employees", "$freelancers"] } } },

    // 6. Unwind and replace root so you end up with a result set.
    { $unwind: '$union' },
    { $replaceRoot: { newRoot: '$union' } }
  ]);

https://cnpnote.tistory.com/entry/MONGODB-MongoDB%EB%A5%BC%EC%9D%B4-onehow%EC%97%90-%EC%97%AC%EB%9F%AC-%EC%BB%AC%EB%A0%89%EC%85%98%EC%97%90%EC%84%9C-%EB%8D%B0%EC%9D%B4%ED%84%B0%EB%A5%BC-%EA%B2%B0%ED%95%A9

 

[MONGODB] MongoDB를이 : one..how에 여러 컬렉션에서 데이터를 결합?

MongoDB를이 : one..how에 여러 컬렉션에서 데이터를 결합? 어떻게 (MongoDB의에서) 하나 개의 모음으로 여러 컬렉션의 데이터를 결합 할 수 있습니까? 내가 만약 그렇다면 그럼 어떻게지도-절감하고 사용할 수 있..

cnpnote.tistory.com

 

Aggregate를 이용한 전형적인 Join 연산 방법은 다음과 같다.

https://stackoverflow.com/questions/53498254/combine-2-collections-data-with-sort-and-pagination-in-mongodb-and-php

 

Combine 2 collections data with sort and pagination in mongodb and php

I have 2 collections user and orders. I want to collect basic info like username, firstname from user collection and sum of amount from order table. I can able to select the data by getting info f...

stackoverflow.com