Note that there are some explanatory texts on larger screens.

plurals
  1. POMongo DB - Sort and Skip within a group
    text
    copied!<p>I am using MongoDB and I want to sort and skip records within a group.</p> <p>Below is a sample data:</p> <pre><code>{ "_id" : ObjectId("51cd7274267d959cb9f95cea"), "creation_time" : 100, "delivered" : true, "id" : 1, "user_id" : 10 } </code></pre> <p>Now what I want is the <code>_id</code> of all the documents per user (<code>user_id</code>) where no. of documents for a user is greater than 4. Also I want the <code>_id</code> of documents after skipping those 4 documents. So if a user has 6 documents, then I want the <code>_id</code> of last 2 documents (sorted by creation_time) so that I can archive those 2 old documents to another db.</p> <p>I am using the following query:</p> <pre><code>db.newsdb.aggregate([ { $match: { delivered: true } }, { $group: { _id: { user_id: "$user_id", creation_time: "$creation_time" } } } ]) </code></pre> <p>Now the problem is that I want to perform <code>$sort</code> and <code>$skip</code> operation on documents for each user and not on the documents of all users. So I want something like:</p> <pre><code>{ $group: { _id: { user_id: "$user_id", creation_time: "$creation_time" } }, $sort: { user_id:1, creation_time:1 }, $skip: 4 } </code></pre> <p>But it seems that mongo db doesn't support it. I am getting the following error:</p> <pre><code>Error: Printing Stack Trace at printStackTrace (src/mongo/shell/utils.js:37:7) at DBCollection.aggregate (src/mongo/shell/collection.js:897:1) at (shell):1:11 Mon Jul 1 14:47:55.762 JavaScript execution failed: aggregate failed: { "errmsg" : "exception: A pipeline stage specification object must contain exactly one field.", "code" : 16435, "ok" : 0 } at src/mongo/shell/collection.js:L898 </code></pre>
 

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