Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If possible, I'd suggest that you set the condition while storing the data so that you can do a quick truth check (<code>isInStudentsList</code>). It would be super fast to do that type of query.</p> <p>Otherwise, there is a relatively complex way of using the Aggregation framework pipeline to do what you want in a single query:</p> <pre><code>db.students.aggregate( {$project: {studentId: 1, studentIdComp: "$students.id"}}, {$unwind: "$studentIdComp"}, {$project : { studentId : 1, isStudentEqual: { $eq : [ "$studentId", "$studentIdComp" ] }}}, {$match: {isStudentEqual: true}}) </code></pre> <p>Given your input example the output would be:</p> <pre><code>{ "result" : [ { "_id" : ObjectId("517b88decd483543a8bdd95b"), "studentId" : 23, "isStudentEqual" : true } ], "ok" : 1 } </code></pre> <p>A brief explanation of the steps:</p> <ol> <li>Build a projection of the document with just <code>studentId</code> and a new field with an array containing just the <code>id</code> (so the first document it would contain <code>[23, 55]</code>.</li> <li>Using that structure, <a href="http://docs.mongodb.org/manual/reference/aggregation/unwind/">$unwind</a>. That creates a new temporary document for each array element in the <code>studentIdComp</code> array.</li> <li>Now, take those documents, and create a new document projection, which continues to have the <code>studentId</code> and adds a new field called <code>isStudentEqual</code> that compares the equality of two fields, the <code>studentId</code> and <code>studentIdComp</code>. Remember that at this point there is a single temporary document that contains those two fields.</li> <li>Finally, check that the comparison value <code>isStudentEqual</code> is true and return those documents (which will contain the original document <code>_id</code> and the <code>studentId</code>. </li> <li>If the student was in the list multiple times, you might need to group the results on <code>studentId</code> or <code>_id</code> to prevent duplicates (but I don't know that you'd need that).</li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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