1 回答

TA贡献1852条经验 获得超1个赞
这是一个纯粹来自 MongoDB shell 的解决方案。
我的解决方案依赖于聚合管道和使用项目操作。在你的问题中你说,
每个文档可以有不同的数组大小 (fetch_dates) 但结构是相同的。
基于此,我认为没有理由必须遍历数据库中的所有文档。相反,您可以只从数据库中提取一个文档并使用它来提出一个应该适用于数据库中所有文档的投影。这是我想出的代码。
function buildProjection(doc, prepend) {
var projection = {};
Object.keys(doc)
.forEach(key => {
var val = doc[key];
var path = prepend==null? key : prepend + '.' + key;
if (key == '_id') {
projection[key] = 1;
} else if ( Array.isArray(val) ) {
projection[key] = { '$slice' : [ '$'+path, -1 ] };
} else if ( typeof val === 'object' && val !== null ) {
projection[key] = buildProjection(val, path);
} else {
projection[key] = 1;
}
});
return projection;
}
/*
* Pull a document out of the database and build the projection based off of it.
* You may want to specify a particular document in the findone
* that you know to be structured correctly
*/
var sample = db.myCollection.findOne({});
var projection = buildProjection(sample, null);
db.myCollection.aggregate([
// apply the build projection
{ $project: projection },
// insert results into another collection
{ $out: 'rebuiltWithLatest' }
]);
我不确定您是否想将结果保存在另一个集合中。我用这个解决方案这样做了。花了几秒钟,但我用 300k 文档运行这个没有问题,这很像你的链接示例。
如果您只想查看文档,请从聚合管道中删除 $output 操作。然后它将返回一个游标对象,您可以迭代该对象以查看其他结果。
- 1 回答
- 0 关注
- 119 浏览
添加回答
举报