上一篇笔记将开始定义的存储结构处理了一下,将FormItems数组中的表单项都拿到mongodb document的最外层,和之前的关系型数据相似,之不过好多列都是动态的,不固定,不过这并无什么影响。结果就是方便咱们更好的查询和统计;还有一点就是转换以后从服务器端返回客户端的对象也是如此,这样更加方便了获取每一个表单项的值(例如渲染列表)。mongodb
咱们的好的应用场景都是分页加载,好多地方都须要知道总的条数。之前呢是弄了两个API:一个是获取查询结果;一个是获取条数。为了这样一个功能要多发送一个API以为有点浪费,以后便上网查了一下,这个问题前辈门已经遇到过了而且解决了,这里只是记录一下。我找到了几种处理方式,下面一一介绍一下。数组
第一种服务器
// $facet New in version 3.4. db.getCollection('FormInstace').aggregate([ { $facet: { totalCount: [{ $match:{FormId:'507048044944691000'} },{ $count: 'totalCount' }], results: [{ $match:{FormId:'507048044944691000'} }] } } ]);
方案二async
// 方案2: async function getQuery() { let query = await db.collection.find({}).skip(5).limit(5); // returns last 5 items in db let countTotal = await query.count() // returns 10-- will not take `skip` or `limit` into consideration let countWithConstraints = await query.count(true) // returns 5 -- will take into consideration `skip` and `limit` return { query, countTotal } }
等待截图……
ide
以上两个方案都来自于:https://stackoverflow.com/questions/21803290/get-a-count-of-total-documents-with-mongodb-when-using-limit优化
方案三spa
// 方案3: db.getCollection('FormInstace').aggregate([ { $match: { "FormItems.key": { $ne: null } } }, { $addFields: { FormValueObj: { $arrayToObject: { $map: { input: "$FormItems", as: "field", in: [ "$$field.key", "$$field.value" ] } } } } }, { $replaceRoot: { newRoot: { $mergeObjects: [ "$FormValueObj", "$$ROOT" ] } } }, { $project: { FormItems:0, FormValueObj:0 } }, { $match:{FormId:'507048044944691000'} }, { $group: { _id: null, count: { $sum: 1 }, results: { $push: '$$ROOT' } } }, { $project:{_id:0,count:1, results: { $slice: [ "$results", 20, 20 ] }} } ]);
方案三参考的是:https://medium.com/@kheengz/mongodb-aggregation-paginated-results-and-a-total-count-using-d2e23a00f5d5 可是上面的链接中也包括了这种方式……无论怎么说达到了咱们想要的结果,而且支持分页!!!就是时间仍是有点长,之后看看还能不能优化,若是有哪位大神有更好的方式,请告知,在这里表示感谢……code