Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm not sure how your application is adding elements to the array but one option is to use <code>$push</code> or <code>$addToSet</code> to add days to the array only when someone is actually working. You can then check the length of the array to know how many days each person has worked. </p> <p>You can also use the aggregation framework (I think this is the better option) to run queries and produce reports. For example, using the following document structure:</p> <pre><code>{ "userId":"user ID" "schedule_begin": "Date", "schedule_end": "Date", "schedule_days_runs": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] } </code></pre> <p>You could run the following query to find out who has worked on a Monday.</p> <pre><code>db.schedule.aggregate([{$unwind:"$schedule_days_runs"},{$group:{"_id":{"working_days":"$schedule_days_runs", "name":"$userId"}}},{$match:{"_id.working_days":"Monday"}},{$sort:{"_id.name":1}}]) </code></pre> <p>This will create separate documents from each element of the array using <code>$unwind</code> and <code>$group</code> them by userId and days worked, then <code>$match</code> with only those people who worked on a Monday. Note the dot notation to reach into embedded documents. The aggregation framework also allows you to redefine fields e.g.<code>"name":"$userId"</code>. An example result from this query is:</p> <pre><code>{ "result" : [ { "_id" : { "working_days" : "Monday", "name" : "Charlie Sheen" } }, { "_id" : { "working_days" : "Monday", "name" : "Donald Duck" } }, { "_id" : { "working_days" : "Monday", "name" : "Superman" } } ], "ok" : 1 </code></pre> <p>}</p> <p>You can do more with the aggregation framework and each part of the query pipes information to the next. So above, $unwind pipes the info through to $group that then matches the document. You can keep going - <a href="http://docs.mongodb.org/manual/reference/aggregation/" rel="nofollow">check out the docs for more detailed info</a>.</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