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?

5
  • Ain't there a findOne() instead of find() ? Commented Oct 31, 2013 at 12:35
  • possible duplicate of MongoDB extract only the selected item in array Commented Oct 31, 2013 at 12:39
  • @johnny already had a look there..but didn't work for me Commented Oct 31, 2013 at 12:40
  • You need to add a projection parameter to your find or findOne call. Commented Oct 31, 2013 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')), )); Commented Oct 31, 2013 at 12:49

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.