title: Is there a way to map array of _id's to documents in one query using MongoDB?
body: <p>I have a MongoDB database and 2 collections inside it: <code>programs</code> and <code>exercises</code>. Documents inside <code>programs</code> collection have an <code>exercises</code> field that contains a string representation of IDs in <code>exercises</code> table, like that:</p>
  
  <pre><code>{
      "_id" : ObjectId("57da8f955cf29df682932ee9"),
        "exercises" : [ 
            "57da8e01d0649e646afaea4e", 
            "57da8e01d0649e646afaea4e", 
            "57da8e01d0649e646afaea4e"
        ]
  }
  </code></pre>
  
  <p>I need to map this array of IDs to array of related <code>exercises</code> objects. The thing is, I need then in precise order and including duplicates. Like in that document earlier, it contains 3 links to the same <code>exercise</code>, and I need to get an array of 3 identical <code>exercise</code>s in response.</p>
  
  <p>Now I am using this query:</p>
  
  <pre><code>db.collection("exercises").find({_id: {$in: exercises.map(exid =&gt; ObjectID(exid)) }}).toArray()
  </code></pre>
  
  <p>This query returns every <code>exercise</code> I need but in the wrong order and without duplicates.</p>
  
  <p>Can I achieve such a result in one query using MongoDB? I know that I can do something like that (didn't test it, just as an example):</p>
  
  <pre><code>exercises.map(exid =&gt; db.collection("exercises").find({id: ObjectID(exid)});
  </code></pre>
  
  <p>Something like this should give me the array I need, but I guess this is not the right way to do it, making a separate query to get a specific <code>exercise</code>.</p>
  
  <p>P.S. I know that I can store <code>exercises</code> in a document itself, not using the external <code>exercises</code> collection for that, but the thing is, some <code>program</code>s may refer to the same <code>exercise</code>, that's why I think I need an external collection for this.</p>