1

所以我的收藏看起来像这样:

{
  "_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 中完成吗?

4

1 回答 1

1

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

例子 :

find( { _id: 1, "products._id": 4 }, { products: { $elemMatch: { _id: 4 } } } ).pretty()
于 2013-10-31T13:19:14.793 回答