2013-01-04 5 views
1

가 나는 다음 컬렉션 MongoDB의에서 'CanvasCollection'라는 이름의 한 나는이 컬렉션에서 배열에서 "50e6fcc2edcbc10613000022"의 id를 가진 이미지 객체를 얻으려면 :MongoDB에서 컬렉션 내의 배열에서 특정 요소를 가져 오는 방법은 무엇입니까?

{ 
"_id": ObjectId("50d1f440471ca84e1f000007"), 
"image": [{ 
    "_id": ObjectId("50e6fcc2edcbc10613000022"), 
    "type": "image", 
    "filename": "50e6fcc2edcbc10613000022.jpg", 
    "origname": "2811879134_7a57d7c586_m.jpg", 
    "filepath": "upload/50e6fcc2edcbc10613000022.jpg", 
    "thumbpath": "upload/50e6fcc2edcbc10613000022_small.jpg",) 
}], 
"text": [{ 
    "_id": ObjectId("50e6eda0edcbc1061300001b"), 
    "content": "Type your text here" 
}] 
} 

이 작동하지 않는 것 :하는 방법을

CanvasCollection.find({'_id': new BSON.ObjectID('50d1f440471ca84e1f000007')}, {'image' : {$elemMatch: {'_id': new BSON.ObjectID('50e6fcc2edcbc10613000022')}}}) 

모든 아이디어를 정확히 :

{ 
    "_id": ObjectId("50e6fcc2edcbc10613000022"), 
    "type": "image", 
    "filename": "50e6fcc2edcbc10613000022.jpg", 
    "origname": "2811879134_7a57d7c586_m.jpg", 
    "filepath": "upload/50e6fcc2edcbc10613000022.jpg", 
    "thumbpath": "upload/50e6fcc2edcbc10613000022_small.jpg",) 
} 

답변

0

당신이 MongoDB를 버전 2.2이처럼 그것을 할 수있는 경우 :

db.CanvasCollection.aggregate({$project: {image:1}},{ $unwind : "$image" },{ $match : {"image._id": ObjectId("50e6fcc2edcbc10613000022")}}) 

(이 몽고 쉘에서이다), 출력은 다음과 같이 될 것이다 : 언 와인드 소개

{ 
"result" : [ 
    { 
     "_id" : ObjectId("50d1f440471ca84e1f000007"), 
     "image" : { 
      "_id" : ObjectId("50e6fcc2edcbc10613000022"), 
      "type": "image", 
      "filename": "50e6fcc2edcbc10613000022.jpg", 
      "origname": "2811879134_7a57d7c586_m.jpg", 
      "filepath": "upload/50e6fcc2edcbc10613000022.jpg", 
      "thumbpath": "upload/50e6fcc2edcbc10613000022_small.jpg" 
     } 
    } 
], 
"ok" : 1 
} 

: http://docs.mongodb.org/manual/reference/aggregation/unwind/.

비슷한 주제 : Retrieve only the queried element in an object array in MongoDB collection ..

나이가 MongoDB의 버전이 있다면 나는 그것이 불가능하다 생각합니다.

관련 문제