我要数据库MongoDB中的每个第n个文档
这是我收集的大约25万份文件:我要数据库MongoDB中的每个第n个文档,mongodb,mongoose,aggregation-framework,Mongodb,Mongoose,Aggregation Framework,这是我收集的大约25万份文件: { "_id" : ObjectId("5ccfbae47dd9094e30998954"), "date" : "05/02/2019" } { "_id" : ObjectId("5ccfbaff7dd9094e30998956"), "date" : "05/04/2019" } { "_id" : ObjectId("5ccfd7dc6432426a9b4a4785"), "date" : "
{
"_id" : ObjectId("5ccfbae47dd9094e30998954"),
"date" : "05/02/2019"
}
{
"_id" : ObjectId("5ccfbaff7dd9094e30998956"),
"date" : "05/04/2019"
}
{
"_id" : ObjectId("5ccfd7dc6432426a9b4a4785"),
"date" : "05/06/2019"
}
{
"_id" : ObjectId("5ccfd8d96432426a9b4a4788"),
"date" : "05/08/2019"
}
{
"_id" : ObjectId("5cd01ab6c3bb270aa5c12ade"),
"date" : "05/04/2019"
}
{
"_id" : ObjectId("5cd0227abf056b4b82d46ba9"),
"date" : "05/06/2019"
}
我收集了超过25万份文档。我必须从我的收集中获取每N个数据,这样就不会花费更多的时间。
作为经验:-我需要收集的每2份文件,预期的文件如下:
{
"_id" : ObjectId("5ccfbaff7dd9094e30998956"),
"date" : "05/04/2019"
}
{
"_id" : ObjectId("5ccfd8d96432426a9b4a4788"),
"date" : "05/08/2019"
}
{
"_id" : ObjectId("5cd0227abf056b4b82d46ba9"),
"date" : "05/06/2019"
}
这个问题有什么解决办法吗?您可以尝试以下方法:
db.collection.aggregate([
{
"$group": {
"_id": null,
data: { $push: "$$ROOT"}
}
},
{
$project: {
requiredResult: {
$map: {
input: { $range: [ 0, { $size: "$data" }, 2 ] }, // here you can replace 2 with any number (N)
as: "index",
in: { $arrayElemAt: [ "$data", "$$index" ] }
}
}
}
}
])