2017-10-16 1 views
0

중첩 나는 내 컬렉션에 다음과 같은 JSON 문서가 있습니다MongoDB의 쿼리 구조

{ 
    "_id": { 
     "$oid": "59e3a593734d1d62dcbe79c3" 
    } 
    "name": "UserNameKiran" 
    "notebooks": [ 
     { 
      "notebookname": "notebook1", 
      "notes": [ 
       { 
        "name": "noteName" 
       }, 
       { 
        "name": "noteName2" 
       } 
      ] 
     }, 
     { 
      "access": "public", 
      "notebookname": "notebook2", 
      "notes": [ 
       { 
        "name": "noteName" 
       }, 
       { 
        "name": "noteName2" 
       } 
      ] 
     } 
    ] 
}; 

나는 특정 사용자 및 노트북에서 모든 "노트"를 검색 할를. 예 : "notebook1"에 대한 모든 메모.

다음 명령을 시도했지만 결과를 얻을 수 없습니다.

req.db.collection('usernotecollection').find({ 
     "_id": ObjectId(req.params.userId), 
     "notebooks": { 
      "$elemMatch": { 
       "notebookname": "notebook1" 
      } 
     } 
    }, {notes:1}).toArray(function (err, results) { 
     console.log(results); 
    }); 

나는 단지 object_id를 반환하고 그 밖의 결과는 반환하지 않습니다. 내가 뭘 놓치고 있니?

답변

0

find() 호출에 제공하는 두 번째 매개 변수는 {notes:1}입니다. _id :

그것은 notes라는 이름의 속성을 반환 MongoDB를 알려줍니다하지만 투사는 기본 속성을 반환 귀하의 문서에 notes 이름 속성이 없습니다, 투사입니다.

대신 {notebooks:1}에 프로젝트를 계획하셨습니까? 이 모든것을 반환 것이므로 기능상 투영을 제공하는 것과 같습니다.

는 다음과 같은 명령을 실행할 수 있습니다,이 명확하게하기 위해 당신은 둘 다 같은 응답을 반환 것을 볼 수 있습니다 :

req.db.collection('usernotecollection').find({ 
     "_id": ObjectId(req.params.userId), 
     "notebooks": { 
      "$elemMatch": { 
       "notebookname": "notebook1" 
      } 
     } 
    }).toArray(function (err, results) { 
     console.log(results); 
    }); 

req.db.collection('usernotecollection').find({ 
     "_id": ObjectId(req.params.userId), 
     "notebooks": { 
      "$elemMatch": { 
       "notebookname": "notebook1" 
      } 
     } 
    }, {notebooks:1}).toArray(function (err, results) { 
     console.log(results); 
    }); 

하는 경우를, 그러나, 당신이 실제로 원하는 것은 notebooksnotes 속성입니다 하위 문서라면 'notebooks.notes': 1에 프로젝트를 제출할 수 있습니다. 다음의 예는 notebooks.notes에 투사함으로써 만 notebooks.notes을 반환하는 기본 _id 돌출부 제외 : 당신이 당신의 쿼리의 돌출부에 $elemMatch 연산자를 사용할 수있는 배열 요소를 필터링하기 위해

req.db.collection('usernotecollection').find({ 
     "_id": ObjectId(req.params.userId), 
     "notebooks": { 
      "$elemMatch": { 
       "notebookname": "notebook1" 
      } 
     } 
    }, {'notebooks.notes':1, '_id': 0}).toArray(function (err, results) { 
     console.log(results); 
    }); 
+0

분명히 설명해 주셔서 감사합니다. 그러나 특정 노트의 노트를 가져올 수 없습니다. 어떤 이유로 "notebookname": "notebook1"과 일치하지 않습니다. –

+0

Tehre는 'notebooks' 하위 문서에'notebookname'이라는 속성이 없습니다. 아마도 notes.name을 의미 할 것입니다. 일반적으로이 양식의 질문 (_how는이 문서에서 x를 얻을 수 있습니까? _)은 (1) 견본 문서와 함께 가장 잘 질문됩니다. (2) 시도한 쿼리의 예제 및 (3) ** 원하는 출력 **. – glytching

+0

감사합니다. 문제를 해결할 수있었습니다. –

0

합니다.

req.db.collection('usernotecollection').find({ 
    // filter 
    "_id": ObjectId(req.params.userId) 
}, { 
    // projection 
    "notebooks": { 
     "$elemMatch": { 
      "notebookname": "notebook1" 
     } 
    } 
}).toArray(function (err, results) { 
    console.log(results); 
});