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' } }
]);
[MONGODB] MongoDB를이 : one..how에 여러 컬렉션에서 데이터를 결합?
MongoDB를이 : one..how에 여러 컬렉션에서 데이터를 결합? 어떻게 (MongoDB의에서) 하나 개의 모음으로 여러 컬렉션의 데이터를 결합 할 수 있습니까? 내가 만약 그렇다면 그럼 어떻게지도-절감하고 사용할 수 있..
cnpnote.tistory.com
Aggregate를 이용한 전형적인 Join 연산 방법은 다음과 같다.
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