2013-11-22 2 views
0

인터넷을 검색하면서 map-reduce 함수를 통해 mongodb에서 조인을 에뮬레이트 할 수 있다는 것을 알았습니다. 문서를 검토하는 것은 혼란 스러웠습니다.MongoDB에서 Map-Reduce 학습

두 개의 컬렉션이 있습니다. 하나는 한 명의 사용자 목록으로 구성됩니다. 그리고 다른 컬렉션은 모든 사용자의 컬렉션입니다. 나는 모든 친구의 프로필 사진을 가져오고 싶다. 원하는 결과를 얻으려면 mongodb 쿼리를 어떻게 만듭니 까?

사용자 모음 : 각 사용자 수집

{ 
    "_id" : ObjectId("524c194a6e3715ce0a000001"), 
    "email" : "[email protected]", 
    "password" : "", 
    "phone" : "", 
    "salt" : "", 
    "upic" : "someuser2fd2751259bb7519d7b760ffee9b7fce203ad1f34.jpg", 
    "username" : "someuser2" 
} 
{ 
    "_id" : ObjectId("524be475fafb35480a000001"), 
    "email" : "", 
    "password" : "", 
    "phone" : "", 
    "salt" : "", 
    "upic" : "amitverma2522b7a52e054c350f78fd7f3558919f2e2dab58.jpg", 
    "username" : "amitverma" 
} 

프렌드 :

{ 
    "_id" : ObjectId("526547ed2389630000000001"), 
    "friends" : [ 
     { 
      "_id" : ObjectId("524be475fafb35480a000001"), 
      "username" : "amitverma" 
     }, 
      { 
      "_id" : ObjectId("524be475fafb35480a000001"), 
      "username" : "someuser2" 
     } 

    ], 
    "upic" : "macbookfd2751259bb7519d7b760ffee9b7fce203ad1f34.jpg", 
    "username" : "someuser" 
} 

도움말을 감상 할 수있다.

+0

여러 컬렉션을 동일한 쿼리에 불가능 http://stackoverflow.com/questions/6502541/mongodb-query-multiple-collections-at-once – zamnuts

답변

0

권장되는 권장 사항이 아니기 때문에 공식적인 문서가 없습니다. 똑같은 결과를 똑같은 컬렉션으로 조심스럽게 출력하는 여러 번 통과해야하는 작업은 복잡합니다.

친구 목록을 수집하고 $in 연산자 (reference)를 사용하여 사용자를 가져오고 필요한 필드 (예 : 이미지) 만 포함되도록 결과를 투사하는 것이 더 나을 것입니다.

이미지 경로를 불필요하게 요청하지 않으려면 이러한 결과를 로컬에 캐시하는 것이 가장 이상적입니다. 다음은 쉘에서 작동해야 테스트되지 않은 코드 :

db.friends.find({ username: 'someuser'}).forEach(friend_list) { 
    // this would gather the list of friend's _ids 
    // the _id will be passed as an array for the $in operator 
    var friends = friend_list.friends.map(function(friend) { return this._id; }); 
    // gather up the images for each of the friends 
    var upics = db.users.find({_id : { $in : friends }}, 
      { _id: 1, upic: 1 }).toArray(); 
    // now, do something with upics -- outside of the MongoDB shell, this will 
    // return asynchronously .... 
}); 
+0

하지만, 나는 여기에 2 개의 다른 콜렉션을 가지고 일하고있다. 어떻게 도움이 될까요? – amit

+0

두 번째 컬렉션으로 ID를 전달합니다. – WiredPrairie

+0

당신이 가리킬 수있는 몇 가지 예가 있습니까? – amit