MongoDb 只返回数组中的一个元素


MongoDb return only one element from the array

所以我的集合看起来像这样:

{
  "_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')
                ));

但它返回该集合的整个数组,我只想要一个......这可以在蒙戈完成吗?

如评论中所述,您必须添加投影,更准确地说是$elemMatch。在这种情况下,无需使用聚合框架。

例:

find( { _id: 1, "products._id": 4 }, { products: { $elemMatch: { _id: 4 } } } ).pretty()