所以我的收藏如下:
{
"_id" : ObjectId("52722429d874590c15000029"),
"name" : "Bags",
"products" : [{
"_id" : ObjectId("527225b5d87459b802000029"),
"name" : "Prada",
"description" : "Prada Bag",
"points" : "234",
"validDate" : 1382562000,
"link" : "dasdad",
"code" : "423423424",
"image" : null
}, {
"_id" : ObjectId("5272307ad87459401a00002a"),
"name" : "Gucci",
"description" : "Gucii bag",
"points" : "2342",
"validDate" : 1383170400,
"link" : "dsadada",
"code" : "2342",
"image" : null
}]
}
我想只获得带有_id 527225b5d87459b802000029的产品,我试过这个:
$this->find(array(
'_id' => new \MongoId('52722429d874590c15000029'),
'products._id' => new \MongoId('527225b5d87459b802000029')
));
但它返回该集合的整个数组,我只想要一个......这可以在mongo中完成吗?
答案 0 :(得分:1)
如评论中所述,您必须添加投影,更准确地说是$elemMatch
。在这种情况下,无需使用聚合框架。
示例:
find( { _id: 1, "products._id": 4 }, { products: { $elemMatch: { _id: 4 } } } ).pretty()