How can I speed up this MongoDB query in Mongoose?
<p>I have a tree-like schema that specifies a collection of parents, and a collection of children.</p>

<p>The collection of children will likely have millions of documents - each of which contains a small amount of data, and a reference to the parent that it belongs to which is stored as a string (perhaps my first mistake).</p>

<p>The collection of parents is much smaller, but may still be in the tens of thousands, and will slowly grow over time.  Generally speaking though, a single parent may have as few as 10 children, or as many as 50,000 (possibly more, although somewhat unlikely).</p>

<p>A single child document might look something like this:</p>

<pre><code>{
_id: ObjectId("507f191e810c19729de860ea"),
info: "Here's some info",
timestamp: 1234567890.0,
colour: "Orange",
sequence: 1000,
parent: "12a4567b909c7654d212e45f"
}
</code></pre>

<p>Its corresponding parent record (which lives in a separate collection) might look something like this:</p>

<pre><code>{
_id: ObjectId("12a4567b909c7654d212e45f")
info: "Blah",
timestamp: 1234567890.0
}
</code></pre>

<p>My query in mongoose (which contains the parent ID in the request) looks like this:</p>

<pre><code>/* GET all children with the specified parent ID */
module.exports.childrenFromParent = function(req, res) {
    parentID = req.params.parentID;
    childModel.find({
        "parentid": parentID
    }).sort({"sequence": "asc"}).exec(
        function(err, children) {
            if (!children) {
                sendJSONResponse(res, 404, {
                    "message": "no children found"
                });
                return;
            } else if (err) {
                sendJSONResponse(res, 404, err);
                return;
            }
            sendJSONResponse(res, 200, children);
        }
    );
};
</code></pre>

<p>So basically what's happening is that the query has to search the entire collection of children for any documents that have a parent which matches the provided ID.</p>

<p>I'm currently saving this parent ID as a string in the children collection schema (childModel in the code above), which is probably a bad idea, however, my API is providing the parent ID as a string in the request.</p>

<p>If anyone has any ideas as to how I can either fix my schema or change the query to improve the performance, it would be much appreciated!</p>