1

So my collection looks like this:

{
  "_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
    }]
}

and I want to get only the product with the _id 527225b5d87459b802000029, I tried this:

$this->find(array(
                '_id' => new \MongoId('52722429d874590c15000029'),
                'products._id' => new \MongoId('527225b5d87459b802000029')
                ));

But it returns the entire array for that collection, and I only want one...can this be done in mongo?

Community
  • 1
  • 1
  • Ain't there a `findOne()` instead of `find()` ? – Daniel W. Oct 31 '13 at 12:35
  • possible duplicate of [MongoDB extract only the selected item in array](http://stackoverflow.com/questions/3985214/mongodb-extract-only-the-selected-item-in-array) – JohnnyHK Oct 31 '13 at 12:39
  • @johnny already had a look there..but didn't work for me – user2885793 Oct 31 '13 at 12:40
  • You need to add a projection parameter to your `find` or `findOne` call. – JohnnyHK Oct 31 '13 at 12:44
  • I found the solution using aggregate aggregate(array( array('$match' => array('_id' => '52722429d874590c15000029')), array('$unwind' => '$products'), array('$match' => array('products._id' => '5272307ad87459401a00002a')), )); – user2885793 Oct 31 '13 at 12:49

1 Answers1

1

As mentioned in comments, you have to add a projection, and more precisely an $elemMatch. No need to use the aggregation framework in that case.

Example :

find( { _id: 1, "products._id": 4 }, { products: { $elemMatch: { _id: 4 } } } ).pretty()
Yann Moisan
  • 8,161
  • 8
  • 47
  • 91