Note that there are some explanatory texts on larger screens.

plurals
  1. POMongo aggregation framework, Sort and then group not working
    text
    copied!<p>I am trying sort data by date first and then group on another field. It is not working to me.</p> <p><em><strong>The question I am trying to answer is: Select the most recent distinct cid?</em></strong></p> <p>given this data:</p> <pre><code>db.summary.save({"lid" : 5, "date" : 5, "cid" : 2, "circles" : [ 2 ] }) db.summary.save({"lid" : 2, "date" : 2, "cid" : 1, "circles" : [ 2 ] }) db.summary.save({"lid" : 4, "date" : 0, "cid" : 3, "circles" : [ 2 ] }) db.summary.save({"lid" : 3, "date" : 3, "cid" : 2, "circles" : [ 2 ] }) db.summary.save({"lid" : 1, "date" : 1, "cid" : 1, "circles" : [ 2 ] }) db.summary.aggregate( {$match :{circles: 2}, $sort: {date: -1}, $group: {_id: '$cid'}} ) </code></pre> <p>I am doing a match first on circles, then a sort on date, then a group on cid</p> <p>The result I am getting: </p> <pre><code>{ "result" : [ { "_id" : 3 }, { "_id" : 1 }, { "_id" : 2 } ], "ok" : 1 } </code></pre> <p><strong>Here is my analysis:</strong></p> <p>before matching or sorting by date, the data was:</p> <pre><code>"lid" : 5, "date" : 5, "cid" : 2 "lid" : 2, "date" : 2, "cid" : 1 "lid" : 4, "date" : 0, "cid" : 3 "lid" : 3, "date" : 3, "cid" : 2 "lid" : 1, "date" : 1, "cid" : 1 </code></pre> <p>After sorting by date, the data set would be:</p> <pre><code>"lid" : 5, "date" : 5, "cid" : 2 "lid" : 3, "date" : 3, "cid" : 2 "lid" : 2, "date" : 2, "cid" : 1 "lid" : 1, "date" : 1, "cid" : 1 "lid" : 4, "date" : 0, "cid" : 3 </code></pre> <p>So after grouping, the result I expect is:</p> <pre><code>{ "result" : [ { "_id" : 2 }, { "_id" : 1 }, { "_id" : 3 } ], "ok" : 1 } </code></pre> <p>What query does solve my problem?</p> <p>Why is the current query not working for me?</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