mongodb - Mongo DB - Sort and Skip within a group -


i using mongodb , want sort , skip records within group.

below sample data:

{     "_id" : objectid("51cd7274267d959cb9f95cea"),     "creation_time" : 100,     "delivered" : true,     "id" : 1,     "user_id" : 10 } 

now want _id of documents per user (user_id) no. of documents user greater 4. want _id of documents after skipping 4 documents. if user has 6 documents, want _id of last 2 documents (sorted creation_time) can archive 2 old documents db.

i using following query:

db.newsdb.aggregate([ {     $match: {         delivered: true     } }, {     $group: {         _id: {             user_id: "$user_id",             creation_time: "$creation_time"         }     } } ]) 

now problem want perform $sort , $skip operation on documents each user , not on documents of users. want like:

{     $group: {         _id: {             user_id: "$user_id",             creation_time: "$creation_time"         }     },     $sort: {         user_id:1,         creation_time:1     },     $skip: 4 } 

but seems mongo db doesn't support it. getting following error:

error: printing stack trace     @ printstacktrace (src/mongo/shell/utils.js:37:7)     @ dbcollection.aggregate (src/mongo/shell/collection.js:897:1)     @ (shell):1:11 mon jul  1 14:47:55.762 javascript execution failed: aggregate failed: {     "errmsg" : "exception: pipeline stage specification object must contain 1 field.",     "code" : 16435,     "ok" : 0 } @  src/mongo/shell/collection.js:l898 

there no way in aggregation framework.

you need make separate query each user. best can loops on users executing query each give documents not top 4:

[user list].foreach(function(u) {   var listtoarchive = db.newsdb.find({user_id: u},{_id:1}).sort({creation_time:-1}).skip(4);  /* need listtoarchive _id's */ } ) 

Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -