Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm attempting to do something similar. I tried your suggestion of using the GROUP function, but I couldn't keep the embedded documents separate or was doing something incorrectly. </p> <p>I needed to pull/get a subset of embedded documents by ID. Here's how I did it using Map/Reduce:</p> <pre><code>db.parent.mapReduce( function(parent_id, child_ids){ if(this._id == parent_id) emit(this._id, {children: this.children, ids: child_ids}) }, function(key, values){ var toReturn = []; values[0].children.forEach(function(child){ if(values[0].ids.indexOf(product._id.toString()) != -1) toReturn.push(child); }); return {children: toReturn}; }, { mapparams: [ "4d93b112c68c993eae000001", //example parent id ["4d97963ec68c99528d000007", "4debbfd5c68c991bba000014"] //example embedded children ids ] } ).find() </code></pre> <p>I've abstracted my collection name to 'parent' and it's embedded documents to 'children'. I pass in two parameters: The parent document ID and an array of the embedded document IDs that I want to retrieve from the parent. Those parameters are passed in as the third parameter to the mapReduce function.</p> <p>In the map function I find the parent document in the collection (which I'm pretty sure uses the _id index) and emit its id and children to the reduce function.</p> <p>In the reduce function, I take the passed in document and loop through each of the children, collecting the ones with the desired ID. Looping through all the children is not ideal, but I don't know of another way to find by ID on an embedded document. </p> <p>I also assume in the reduce function that there is only one document emitted since I'm searching by ID. If you expect more than one parent_id to match, than you will have to loop through the <code>values</code> array in the reduce function.</p> <p>I hope this helps someone out there, as I googled everywhere with no results. Hopefully we'll see a built in feature soon from MongoDB, but until then I have to use this.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload