2013-01-04 60 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我认为这是不可能的。