根据日期统计出某些手机号记录数 1 2 3 4 5 6 7 8 9 10 var data = db.spinetmp.aggregate([ {$match: {status: 'visable' , checkuserid: {$in : ['156****5285' , '156****5194' , '137****8875' , '158****1125' ]}}}, {$project: {mobile: '$checkuserid' , date: {$dateToString: {format: "%Y-%m-%d" , date: "$version" }}}}, {$group: {_id: {mobile: '$mobile' , date: "$date" }, count: {$sum: 1 }}}, {$sort: {'_id.mobile' : 1 , '_id.date' : -1 }} ]); data.map(function (item ) { return item._id.mobile + ',' + item._id.date + ',' + item.count; }).join("\n" );
倒出用户书单的描述和书的推荐语 1 2 3 4 5 6 7 8 9 10 11 12 var users = db.user.find({mobile_number: {$in : ['156****6041' , '155****4511' , '136****5641' ]}}, {_id: 0 , mobile_number: 1 , user_id: 1 });users.map(function (item ) { item.floors = db.floor.find({user_id: item.user_id, type: {$exists: false }}, {user_id: 1 , name: 1 , desc: 1 , item_list: 1 }).toArray(); item.floors = item.floors.map(function (item ) { item.item_list = item.item_list.map(function (item ) { return db.item.findOne({bid: item}, {bid: 1 , title: 1 , remark: 1 }); }); return item; }); return item; });
根据出版社和书排出用户收藏最多的书 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 rs.slaveOk(); var data = db.library.aggregate([ {$group: {_id: {publisher: '$publisher' , bid: '$bid' , title: '$title' }, count: {$sum: 1 }}} ]); data .toArray() .sort(function (a, b ) { return b.count - a.count; }) .map(function (item ) { return item._id.publisher + ',' + item._id.bid + ',' + item._id.title + ',' + item.count; }) .join("\n" );
查出指定出版社前10名的书籍 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 rs.slaveOk(); var publishers = [ '人民文学出版社' , '上海译文出版社' , '中华书局' , '中信出版社' , '商务印书馆' , '生活·读书·新知三联书店' , '广西师范大学出版社' , '译林出版社' , '新星出版社' , '南海出版公司' ]; var data = db.library.aggregate([ {$match: {publisher: {$in : publishers}}}, {$group: {_id: {publisher: '$publisher' , title: '$title' }, count: {$sum: 1 }}} ]); var findIndex = function (fn ) { var i = 0 , r; while (this .length > i && !(r = fn(this [i], i, this ))) i++; return r ? i : -1 ; }; data .toArray() .sort(function (a, b ) { return (publishers.indexOf(a._id.publisher) - publishers.indexOf(b._id.publisher)) || (b.count - a.count); }) .filter(function (item, index, ary ) { return index < (findIndex.call(ary, function (data ) { return item._id.publisher === data._id.publisher; }) + 10 ); }) .map(function (item ) { return item._id.publisher + ',' + item._id.title + ',' + item.count; }) .join("\n" );
ifNull的使用 1 db.library.aggregate([
{$match: {user_id: '763532fec962ca3f5c96cd024860a43a'}},
{$project: {read_status: {$ifNull: ["$read_status", "unread"]}}},
{$group: {_id: '$read_status', total: {$sum: 1}}}
]);