2017-12-24 4 views
0

이것은 추상적 인 예이지만, 누군가 그것을 해결할 수 있다면 영원히 감사 할 것입니다.MongoDB join on

관련 레코드의 필드를 기반으로 검색을 수행하려고합니다. 이 예제에서는 parent_subject 필드를 사용하여 중첩 된 제목의 계층 구조가 있습니다. 내 MongoDB의에서

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 
var subjectSchema = new Schema({ 
    url: { type: String, required: true, unique: true }, 
    title: { type: String, required: true, unique: true }, 
    parent_subject: this 
}); 
module.exports = mongoose.model('Subject', subjectSchema); 

일부 기록 :

{ 
    "_id" : ObjectId("5a3857f1afeb498c9533aef1"), 
    "title" : "Sport", 
    "url" : "sport", 
    "__v" : 0 
}, 
{ 
    "_id" : ObjectId("5a3d9a409c0973976f7889c6"), 
    "title" : "Cycling", 
    "__v" : 0, 
    "parent_subject" : ObjectId("5a3857f1afeb498c9533aef1"), 
    "url" : "cycling" 
}, 
{ 
    "_id" : ObjectId("5a3d9a7e9c0973976f788b48"), 
    "title" : "Mountain Biking", 
    "__v" : 0, 
    "parent_subject" : ObjectId("5a3d9a409c0973976f7889c6"), 
    "url" : "mountain biking" 
} 

내가 부모 레코드의 필드를 기준으로이 데이터를 조회 할 수있는 방법을 알고 싶습니다 이것은 내가 사용했던 몽구스 정의입니다. 예를 들어, 제목이 "스포츠"인 부모 주제가있는 모든 주제를 찾고 싶습니다. SQL에서 다음 쿼리를 수행 할 것입니다.

SELECT * 
FROM subject 
    INNER JOIN subject AS parentSubject 
     ON subject.parent_subject = parentSubject.id 
WHERE parentSubject.title = "Sport"; 

MongoDB를 사용하면 어떻게됩니까?

답변

-1

mongoDB의 핵심은 NOSQl이므로 조인을 사용할 수 없다는 것입니다. 가장 좋은 방법은 먼저 parentSubject를 얻는 것입니다. id입니다. 그런 다음 그와 관련된 주제로 가십시오. id.

데이터에 이미 subject.parent_subject이 있으므로 매우 쉽게 수행 할 수 있습니다.

+0

을 볼 수 있습니다 더 참고로이

'Subject.aggregate([ { $lookup: { from: "parentSubject", localField: "parent_subject", foreignField: "id" as: "parentSubject" } }, {$unwind:"$parentSubject"}, {$match:{"$parentSubject.title":"Sport"}} ])' 

위해 MongoDB를 집계 파이프 라인 및 조회를 사용할 수 있습니다 - 당신이 정말 유래 – readikus