복붙노트

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

MONGODB

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

어떻게 (MongoDB의에서) 하나 개의 모음으로 여러 컬렉션의 데이터를 결합 할 수 있습니까?

내가 만약 그렇다면 그럼 어떻게지도-절감하고 사용할 수 있습니까?

내가 초보자 이대로 크게 몇 가지 예제를 부탁드립니다.

해결법

  1. ==============================

    1.이 실시간으로 할 수는 없지만, 당신은 1.8 이상지도 축소 / MongoDB를의 옵션에서 "감소"를 사용하여 병합 데이터에 여러 번 함께지도-감소 실행할 수 있습니다 (http://www.mongodb.org/ 참조 디스플레이 / DOCS / 맵리 듀스 # 맵리 듀스 - Outputoptions). 당신은 당신이 _id로 사용할 수있는 두 컬렉션을 몇 가지 핵심이 필요합니다.

    이 실시간으로 할 수는 없지만, 당신은 1.8 이상지도 축소 / MongoDB를의 옵션에서 "감소"를 사용하여 병합 데이터에 여러 번 함께지도-감소 실행할 수 있습니다 (http://www.mongodb.org/ 참조 디스플레이 / DOCS / 맵리 듀스 # 맵리 듀스 - Outputoptions). 당신은 당신이 _id로 사용할 수있는 두 컬렉션을 몇 가지 핵심이 필요합니다.

    예를 들어, 당신이 사용자 수집 및 의견 수집이 있다고 가정하자 각 주석에 대한 몇 가지 사용자 인구 통계 학적 정보를 가지고 새 컬렉션을 갖고 싶어.

    하자가 사용자의 컬렉션 다음 필드가 말한다 :

    그리고 의견 수집은 다음과 같은 필드가 있습니다 :

    당신은 /이지도를 할 것입니다 감소 :

    var mapUsers, mapComments, reduce;
    db.users_comments.remove();
    
    // setup sample data - wouldn't actually use this in production
    db.users.remove();
    db.comments.remove();
    db.users.save({firstName:"Rich",lastName:"S",gender:"M",country:"CA",age:"18"});
    db.users.save({firstName:"Rob",lastName:"M",gender:"M",country:"US",age:"25"});
    db.users.save({firstName:"Sarah",lastName:"T",gender:"F",country:"US",age:"13"});
    var users = db.users.find();
    db.comments.save({userId: users[0]._id, "comment": "Hey, what's up?", created: new ISODate()});
    db.comments.save({userId: users[1]._id, "comment": "Not much", created: new ISODate()});
    db.comments.save({userId: users[0]._id, "comment": "Cool", created: new ISODate()});
    // end sample data setup
    
    mapUsers = function() {
        var values = {
            country: this.country,
            gender: this.gender,
            age: this.age
        };
        emit(this._id, values);
    };
    mapComments = function() {
        var values = {
            commentId: this._id,
            comment: this.comment,
            created: this.created
        };
        emit(this.userId, values);
    };
    reduce = function(k, values) {
        var result = {}, commentFields = {
            "commentId": '', 
            "comment": '',
            "created": ''
        };
        values.forEach(function(value) {
            var field;
            if ("comment" in value) {
                if (!("comments" in result)) {
                    result.comments = [];
                }
                result.comments.push(value);
            } else if ("comments" in value) {
                if (!("comments" in result)) {
                    result.comments = [];
                }
                result.comments.push.apply(result.comments, value.comments);
            }
            for (field in value) {
                if (value.hasOwnProperty(field) && !(field in commentFields)) {
                    result[field] = value[field];
                }
            }
        });
        return result;
    };
    db.users.mapReduce(mapUsers, reduce, {"out": {"reduce": "users_comments"}});
    db.comments.mapReduce(mapComments, reduce, {"out": {"reduce": "users_comments"}});
    db.users_comments.find().pretty(); // see the resulting collection
    

    이 시점에서 병합 된 데이터가 포함 된 새 컬렉션이라는 users_comments을해야합니다 그리고 당신은 지금 사용할 수 있습니다. 값이 감소 문서의 최상위에없는 -이 감소 컬렉션은 모든 당신이 당신의지도 기능에서 방출 된 후 값이 값 키 내부의 하위 오브젝트 모두의 핵심 인 _id 있습니다.

    이것은 다소 간단한 예입니다. 당신이 감소 수집을 구축하고 유지하기 원하는 수만큼 더 많은 컬렉션에 이것을 반복 할 수 있습니다. 또한 그 과정에서 데이터의 요약 및 집계를 할 수 있습니다. 가능성이 하나가 집계 기존 필드를 유지하는 것은 더 복잡해의 논리로 기능을 감소보다 더 정의하는 것입니다.

    또한 배열에서 해당 사용자의 의견을 모두 각 사용자에 대해 하나 개의 문서가 지금이 있음을 알게 될 것이다. 우리는 일대일 관계가 아닌 일대 데이터를 병합 한 경우, 평평 할 것입니다 그리고 당신은 단순히이 같은 기능을 감소 사용할 수 있습니다 :

    reduce = function(k, values) {
        var result = {};
        values.forEach(function(value) {
            var field;
            for (field in value) {
                if (value.hasOwnProperty(field)) {
                    result[field] = value[field];
                }
            }
        });
        return result;
    };
    

    이 코멘트 당 하나 개의 문서 그래서 당신이 users_comments 수집을 평평하게하려면, 추가로이 실행 :

    var map, reduce;
    map = function() {
        var debug = function(value) {
            var field;
            for (field in value) {
                print(field + ": " + value[field]);
            }
        };
        debug(this);
        var that = this;
        if ("comments" in this.value) {
            this.value.comments.forEach(function(value) {
                emit(value.commentId, {
                    userId: that._id,
                    country: that.value.country,
                    age: that.value.age,
                    comment: value.comment,
                    created: value.created,
                });
            });
        }
    };
    reduce = function(k, values) {
        var result = {};
        values.forEach(function(value) {
            var field;
            for (field in value) {
                if (value.hasOwnProperty(field)) {
                    result[field] = value[field];
                }
            }
        });
        return result;
    };
    db.users_comments.mapReduce(map, reduce, {"out": "comments_with_demographics"});
    

    이 기술은 확실히 즉시 수행 할 수 없습니다. 그것은 주기적으로 병합 된 데이터를 갱신 그런 cron 작업 또는 무언가에 적합합니다. 당신은 아마 당신이 코멘트 작성 시간에 인덱스 comments_with_demographics에 있었다 그렇다면, (데이터가 값 키 내부에 여전히 있음을 유의하십시오 당신이 신속하게 실행에 대해 수행해야합니다 쿼리를 만들기 위해 새로운 컬렉션 ensureIndex을 실행하려는 것, 그것을 db.comments_with_demographics.ensureIndex이 될 것입니다 ({ "value.created": 1});

  2. ==============================

    2.MongoDB를 3.2은 이제 하나가 $ 조회 집계 단계를 통해 하나에 여러 컬렉션의 데이터를 결합 할 수 있습니다. 실제 예를 들어, 당신은 책에 대한 데이터가 두 개의 서로 다른 컬렉션으로 분할 가지고 말을 할 수 있습니다.

    MongoDB를 3.2은 이제 하나가 $ 조회 집계 단계를 통해 하나에 여러 컬렉션의 데이터를 결합 할 수 있습니다. 실제 예를 들어, 당신은 책에 대한 데이터가 두 개의 서로 다른 컬렉션으로 분할 가지고 말을 할 수 있습니다.

    먼저 수집,라는 책에서 다음 데이터를 갖는

    {
        "isbn": "978-3-16-148410-0",
        "title": "Some cool book",
        "author": "John Doe"
    }
    {
        "isbn": "978-3-16-148999-9",
        "title": "Another awesome book",
        "author": "Jane Roe"
    }
    

    그리고 두 번째 컬렉션이라고 books_selling_data 다음 데이터를 갖는

    {
        "_id": ObjectId("56e31bcf76cdf52e541d9d26"),
        "isbn": "978-3-16-148410-0",
        "copies_sold": 12500
    }
    {
        "_id": ObjectId("56e31ce076cdf52e541d9d28"),
        "isbn": "978-3-16-148999-9",
        "copies_sold": 720050
    }
    {
        "_id": ObjectId("56e31ce076cdf52e541d9d29"),
        "isbn": "978-3-16-148999-9",
        "copies_sold": 1000
    }
    

    두 컬렉션을 병합하려면 다음과 같은 방법으로 $ 조회를 사용의 문제입니다 :

    db.books.aggregate([{
        $lookup: {
                from: "books_selling_data",
                localField: "isbn",
                foreignField: "isbn",
                as: "copies_sold"
            }
    }])
    

    이 집계 한 후, 책 수집은 다음과 같이 표시됩니다

    {
        "isbn": "978-3-16-148410-0",
        "title": "Some cool book",
        "author": "John Doe",
        "copies_sold": [
            {
                "_id": ObjectId("56e31bcf76cdf52e541d9d26"),
                "isbn": "978-3-16-148410-0",
                "copies_sold": 12500
            }
        ]
    }
    {
        "isbn": "978-3-16-148999-9",
        "title": "Another awesome book",
        "author": "Jane Roe",
        "copies_sold": [
            {
                "_id": ObjectId("56e31ce076cdf52e541d9d28"),
                "isbn": "978-3-16-148999-9",
                "copies_sold": 720050
            },
            {
                "_id": ObjectId("56e31ce076cdf52e541d9d28"),
                "isbn": "978-3-16-148999-9",
                "copies_sold": 1000
            }
        ]
    }
    

    몇 가지를 유의해야합니다 :

    당신이 가진 두 컬렉션을 통합하려는 경우 그래서, 결론으로,이 경우, 총 판매 사본 플랫 copies_sold 필드, 당신은 아마 중간 컬렉션을 사용, 조금 더 일해야합니다 것을 뜻하고, 마지막 컬렉션에 밖으로 $합니다.

  3. ==============================

    3.MongoDB를에 더 대량 삽입이없는 경우, 우리는 루프 big_collection에 하나 하나 small_collection에서 그들을 삽입 모든 객체 :

    MongoDB를에 더 대량 삽입이없는 경우, 우리는 루프 big_collection에 하나 하나 small_collection에서 그들을 삽입 모든 객체 :

    db.small_collection.find().forEach(function(obj){ 
       db.big_collection.insert(obj)
    });
    
  4. ==============================

    4.$ 조회와 매우 기본적인 예.

    $ 조회와 매우 기본적인 예.

    db.getCollection('users').aggregate([
        {
            $lookup: {
                from: "userinfo",
                localField: "userId",
                foreignField: "userId",
                as: "userInfoData"
            }
        },
        {
            $lookup: {
                from: "userrole",
                localField: "userId",
                foreignField: "userId",
                as: "userRoleData"
            }
        },
        { $unwind: { path: "$userInfoData", preserveNullAndEmptyArrays: true }},
        { $unwind: { path: "$userRoleData", preserveNullAndEmptyArrays: true }}
    ])
    

    여기에 사용되는

     { $unwind: { path: "$userInfoData", preserveNullAndEmptyArrays: true }}, 
     { $unwind: { path: "$userRoleData", preserveNullAndEmptyArrays: true }}
    

    대신에

    { $unwind:"$userRoleData"} 
    { $unwind:"$userRoleData"}
    

    {$ 언 와인드 : "$ userRoleData"} 때문에 일치하는 기록이 조회 $로 찾을 수없는 경우이 비어 있거나 0 결과를 반환합니다.

  5. ==============================

    5.집계에서 여러 컬렉션에 대해 여러 $ 조회를 사용

    집계에서 여러 컬렉션에 대해 여러 $ 조회를 사용

    질문:

    db.getCollection('servicelocations').aggregate([
      {
        $match: {
          serviceLocationId: {
            $in: ["36728"]
          }
        }
      },
      {
        $lookup: {
          from: "orders",
          localField: "serviceLocationId",
          foreignField: "serviceLocationId",
          as: "orders"
        }
      },
      {
        $lookup: {
          from: "timewindowtypes",
          localField: "timeWindow.timeWindowTypeId",
          foreignField: "timeWindowTypeId",
          as: "timeWindow"
        }
      },
      {
        $lookup: {
          from: "servicetimetypes",
          localField: "serviceTimeTypeId",
          foreignField: "serviceTimeTypeId",
          as: "serviceTime"
        }
      },
      {
        $unwind: "$orders"
      },
      {
        $unwind: "$serviceTime"
      },
      {
        $limit: 14
      }
    ])
    

    결과:

    {
        "_id" : ObjectId("59c3ac4bb7799c90ebb3279b"),
        "serviceLocationId" : "36728",
        "regionId" : 1.0,
        "zoneId" : "DXBZONE1",
        "description" : "AL HALLAB REST EMIRATES MALL",
        "locationPriority" : 1.0,
        "accountTypeId" : 1.0,
        "locationType" : "SERVICELOCATION",
        "location" : {
            "makani" : "",
            "lat" : 25.119035,
            "lng" : 55.198694
        },
        "deliveryDays" : "MTWRFSU",
        "timeWindow" : [ 
            {
                "_id" : ObjectId("59c3b0a3b7799c90ebb32cde"),
                "timeWindowTypeId" : "1",
                "Description" : "MORNING",
                "timeWindow" : {
                    "openTime" : "06:00",
                    "closeTime" : "08:00"
                },
                "accountId" : 1.0
            }, 
            {
                "_id" : ObjectId("59c3b0a3b7799c90ebb32cdf"),
                "timeWindowTypeId" : "1",
                "Description" : "MORNING",
                "timeWindow" : {
                    "openTime" : "09:00",
                    "closeTime" : "10:00"
                },
                "accountId" : 1.0
            }, 
            {
                "_id" : ObjectId("59c3b0a3b7799c90ebb32ce0"),
                "timeWindowTypeId" : "1",
                "Description" : "MORNING",
                "timeWindow" : {
                    "openTime" : "10:30",
                    "closeTime" : "11:30"
                },
                "accountId" : 1.0
            }
        ],
        "address1" : "",
        "address2" : "",
        "phone" : "",
        "city" : "",
        "county" : "",
        "state" : "",
        "country" : "",
        "zipcode" : "",
        "imageUrl" : "",
        "contact" : {
            "name" : "",
            "email" : ""
        },
        "status" : "ACTIVE",
        "createdBy" : "",
        "updatedBy" : "",
        "updateDate" : "",
        "accountId" : 1.0,
        "serviceTimeTypeId" : "1",
        "orders" : [ 
            {
                "_id" : ObjectId("59c3b291f251c77f15790f92"),
                "orderId" : "AQ18O1704264",
                "serviceLocationId" : "36728",
                "orderNo" : "AQ18O1704264",
                "orderDate" : "18-Sep-17",
                "description" : "AQ18O1704264",
                "serviceType" : "Delivery",
                "orderSource" : "Import",
                "takenBy" : "KARIM",
                "plannedDeliveryDate" : ISODate("2017-08-26T00:00:00.000Z"),
                "plannedDeliveryTime" : "",
                "actualDeliveryDate" : "",
                "actualDeliveryTime" : "",
                "deliveredBy" : "",
                "size1" : 296.0,
                "size2" : 3573.355,
                "size3" : 240.811,
                "jobPriority" : 1.0,
                "cancelReason" : "",
                "cancelDate" : "",
                "cancelBy" : "",
                "reasonCode" : "",
                "reasonText" : "",
                "status" : "",
                "lineItems" : [ 
                    {
                        "ItemId" : "BNWB020",
                        "size1" : 15.0,
                        "size2" : 78.6,
                        "size3" : 6.0
                    }, 
                    {
                        "ItemId" : "BNWB021",
                        "size1" : 20.0,
                        "size2" : 252.0,
                        "size3" : 11.538
                    }, 
                    {
                        "ItemId" : "BNWB023",
                        "size1" : 15.0,
                        "size2" : 285.0,
                        "size3" : 16.071
                    }, 
                    {
                        "ItemId" : "CPMW112",
                        "size1" : 3.0,
                        "size2" : 25.38,
                        "size3" : 1.731
                    }, 
                    {
                        "ItemId" : "MMGW001",
                        "size1" : 25.0,
                        "size2" : 464.375,
                        "size3" : 46.875
                    }, 
                    {
                        "ItemId" : "MMNB218",
                        "size1" : 50.0,
                        "size2" : 920.0,
                        "size3" : 60.0
                    }, 
                    {
                        "ItemId" : "MMNB219",
                        "size1" : 50.0,
                        "size2" : 630.0,
                        "size3" : 40.0
                    }, 
                    {
                        "ItemId" : "MMNB220",
                        "size1" : 50.0,
                        "size2" : 416.0,
                        "size3" : 28.846
                    }, 
                    {
                        "ItemId" : "MMNB270",
                        "size1" : 50.0,
                        "size2" : 262.0,
                        "size3" : 20.0
                    }, 
                    {
                        "ItemId" : "MMNB302",
                        "size1" : 15.0,
                        "size2" : 195.0,
                        "size3" : 6.0
                    }, 
                    {
                        "ItemId" : "MMNB373",
                        "size1" : 3.0,
                        "size2" : 45.0,
                        "size3" : 3.75
                    }
                ],
                "accountId" : 1.0
            }, 
            {
                "_id" : ObjectId("59c3b291f251c77f15790f9d"),
                "orderId" : "AQ137O1701240",
                "serviceLocationId" : "36728",
                "orderNo" : "AQ137O1701240",
                "orderDate" : "18-Sep-17",
                "description" : "AQ137O1701240",
                "serviceType" : "Delivery",
                "orderSource" : "Import",
                "takenBy" : "KARIM",
                "plannedDeliveryDate" : ISODate("2017-08-26T00:00:00.000Z"),
                "plannedDeliveryTime" : "",
                "actualDeliveryDate" : "",
                "actualDeliveryTime" : "",
                "deliveredBy" : "",
                "size1" : 28.0,
                "size2" : 520.11,
                "size3" : 52.5,
                "jobPriority" : 1.0,
                "cancelReason" : "",
                "cancelDate" : "",
                "cancelBy" : "",
                "reasonCode" : "",
                "reasonText" : "",
                "status" : "",
                "lineItems" : [ 
                    {
                        "ItemId" : "MMGW001",
                        "size1" : 25.0,
                        "size2" : 464.38,
                        "size3" : 46.875
                    }, 
                    {
                        "ItemId" : "MMGW001-F1",
                        "size1" : 3.0,
                        "size2" : 55.73,
                        "size3" : 5.625
                    }
                ],
                "accountId" : 1.0
            }, 
            {
                "_id" : ObjectId("59c3b291f251c77f15790fd8"),
                "orderId" : "AQ110O1705036",
                "serviceLocationId" : "36728",
                "orderNo" : "AQ110O1705036",
                "orderDate" : "18-Sep-17",
                "description" : "AQ110O1705036",
                "serviceType" : "Delivery",
                "orderSource" : "Import",
                "takenBy" : "KARIM",
                "plannedDeliveryDate" : ISODate("2017-08-26T00:00:00.000Z"),
                "plannedDeliveryTime" : "",
                "actualDeliveryDate" : "",
                "actualDeliveryTime" : "",
                "deliveredBy" : "",
                "size1" : 60.0,
                "size2" : 1046.0,
                "size3" : 68.0,
                "jobPriority" : 1.0,
                "cancelReason" : "",
                "cancelDate" : "",
                "cancelBy" : "",
                "reasonCode" : "",
                "reasonText" : "",
                "status" : "",
                "lineItems" : [ 
                    {
                        "ItemId" : "MMNB218",
                        "size1" : 50.0,
                        "size2" : 920.0,
                        "size3" : 60.0
                    }, 
                    {
                        "ItemId" : "MMNB219",
                        "size1" : 10.0,
                        "size2" : 126.0,
                        "size3" : 8.0
                    }
                ],
                "accountId" : 1.0
            }
        ],
        "serviceTime" : {
            "_id" : ObjectId("59c3b07cb7799c90ebb32cdc"),
            "serviceTimeTypeId" : "1",
            "serviceTimeType" : "nohelper",
            "description" : "",
            "fixedTime" : 30.0,
            "variableTime" : 0.0,
            "accountId" : 1.0
        }
    }
    
  6. ==============================

    6.는 'SQL UNION'방식으로 MongoDB의 노동 조합을하는 것은 하나의 쿼리에서, 조회와 함께 집계를 사용 가능하다. 여기에 내가 MongoDB를 4.0에 맞는지 테스트 한 예입니다 :

    는 'SQL UNION'방식으로 MongoDB의 노동 조합을하는 것은 하나의 쿼리에서, 조회와 함께 집계를 사용 가능하다. 여기에 내가 MongoDB를 4.0에 맞는지 테스트 한 예입니다 :

    // 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' } }
      ]);
    

    여기 그것이 작동하는 방법의 설명입니다 :

  7. ==============================

    7.Mongorestore이 문제는 두 개의 모음을 결합에 사용될 수 있도록, 이미 데이터베이스에 어떤 위에 추가의 기능이 있습니다 :

    Mongorestore이 문제는 두 개의 모음을 결합에 사용될 수 있도록, 이미 데이터베이스에 어떤 위에 추가의 기능이 있습니다 :

    아직 시도하지 않았다, 그러나지도보다 더 빠르게 수행 할 수 / 접근 방법을 줄일 수 있습니다.

  8. ==============================

    8.코드 스 니펫. 본 프로그램 포함 스택 오버 플로우에 의례 - ​​여러 게시물.

    코드 스 니펫. 본 프로그램 포함 스택 오버 플로우에 의례 - ​​여러 게시물.

     db.cust.drop();
     db.zip.drop();
     db.cust.insert({cust_id:1, zip_id: 101});
     db.cust.insert({cust_id:2, zip_id: 101});
     db.cust.insert({cust_id:3, zip_id: 101});
     db.cust.insert({cust_id:4, zip_id: 102});
     db.cust.insert({cust_id:5, zip_id: 102});
    
     db.zip.insert({zip_id:101, zip_cd:'AAA'});
     db.zip.insert({zip_id:102, zip_cd:'BBB'});
     db.zip.insert({zip_id:103, zip_cd:'CCC'});
    
    mapCust = function() {
        var values = {
            cust_id: this.cust_id
        };
        emit(this.zip_id, values);
    };
    
    mapZip = function() {
        var values = {
        zip_cd: this.zip_cd
        };
        emit(this.zip_id, values);
    };
    
    reduceCustZip =  function(k, values) {
        var result = {};
        values.forEach(function(value) {
        var field;
            if ("cust_id" in value) {
                if (!("cust_ids" in result)) {
                    result.cust_ids = [];
                }
                result.cust_ids.push(value);
            } else {
        for (field in value) {
            if (value.hasOwnProperty(field) ) {
                    result[field] = value[field];
            }
             };  
           }
          });
           return result;
    };
    
    
    db.cust_zip.drop();
    db.cust.mapReduce(mapCust, reduceCustZip, {"out": {"reduce": "cust_zip"}});
    db.zip.mapReduce(mapZip, reduceCustZip, {"out": {"reduce": "cust_zip"}});
    db.cust_zip.find();
    
    
    mapCZ = function() {
        var that = this;
        if ("cust_ids" in this.value) {
            this.value.cust_ids.forEach(function(value) {
                emit(value.cust_id, {
                    zip_id: that._id,
                    zip_cd: that.value.zip_cd
                });
            });
        }
    };
    
    reduceCZ = function(k, values) {
        var result = {};
        values.forEach(function(value) {
            var field;
            for (field in value) {
                if (value.hasOwnProperty(field)) {
                    result[field] = value[field];
                }
            }
        });
        return result;
    };
    db.cust_zip_joined.drop();
    db.cust_zip.mapReduce(mapCZ, reduceCZ, {"out": "cust_zip_joined"}); 
    db.cust_zip_joined.find().pretty();
    
    
    var flattenMRCollection=function(dbName,collectionName) {
        var collection=db.getSiblingDB(dbName)[collectionName];
    
        var i=0;
        var bulk=collection.initializeUnorderedBulkOp();
        collection.find({ value: { $exists: true } }).addOption(16).forEach(function(result) {
            print((++i));
            //collection.update({_id: result._id},result.value);
    
            bulk.find({_id: result._id}).replaceOne(result.value);
    
            if(i%1000==0)
            {
                print("Executing bulk...");
                bulk.execute();
                bulk=collection.initializeUnorderedBulkOp();
            }
        });
        bulk.execute();
    };
    
    
    flattenMRCollection("mydb","cust_zip_joined");
    db.cust_zip_joined.find().pretty();
    
  9. ==============================

    9.예를 수행 할 수 있습니다 : 오늘 쓴 것을이 유틸리티 기능을 가지고 :

    예를 수행 할 수 있습니다 : 오늘 쓴 것을이 유틸리티 기능을 가지고 :

    function shangMergeCol() {
      tcol= db.getCollection(arguments[0]);
      for (var i=1; i<arguments.length; i++){
        scol= db.getCollection(arguments[i]);
        scol.find().forEach(
            function (d) {
                tcol.insert(d);
            }
        )
      }
    }
    

    당신은 첫 번째 목표 중 하나가 될 것입니다,이 함수에 컬렉션의 수를 전달할 수 있습니다. 나머지 모든 모음을 목표로 전송 될 수있는 소스입니다.

  10. ==============================

    10.당신은 당신의 응용 프로그램 계층에서 그렇게했습니다. 당신이 ORM을 사용하는 경우, 다른 컬렉션에 존재하는 참조를 끌어 주석 (또는 비슷한)를 사용할 수 있습니다. 난 단지 모르핀 일한 및 조회 할 때 내가 코드에서 그것을 자신을 일을 피할 수 있어요 있도록 @Reference 주석이 참조 된 개체를 가져옵니다.

    당신은 당신의 응용 프로그램 계층에서 그렇게했습니다. 당신이 ORM을 사용하는 경우, 다른 컬렉션에 존재하는 참조를 끌어 주석 (또는 비슷한)를 사용할 수 있습니다. 난 단지 모르핀 일한 및 조회 할 때 내가 코드에서 그것을 자신을 일을 피할 수 있어요 있도록 @Reference 주석이 참조 된 개체를 가져옵니다.

  11. from https://stackoverflow.com/questions/5681851/mongodb-combine-data-from-multiple-collections-into-one-how by cc-by-sa and MIT license