Mongodb 如何减少聚合管道中的重复数据?
我有一条管道可以满足我的需要。。。但我认为有些冗余数据可以从管道中删除 预期产量 这就是我希望输出的样子Mongodb 如何减少聚合管道中的重复数据?,mongodb,pipeline,projection,Mongodb,Pipeline,Projection,我有一条管道可以满足我的需要。。。但我认为有些冗余数据可以从管道中删除 预期产量 这就是我希望输出的样子 { "_id": "5ecee2189fdd1b0004056936", "name": "Mike", "history": [ { "_id": "5ecb263c166b8500047c1411", "what": "Log IN" }, { "_id": "5ecb263c166b8500047c14
{
"_id": "5ecee2189fdd1b0004056936",
"name": "Mike",
"history": [
{
"_id": "5ecb263c166b8500047c1411",
"what": "Log IN"
},
{
"_id": "5ecb263c166b8500047c1422",
"what": "Log OUT"
}
]
}
电流输出
这就是当前输出的样子
{
"docs": [
{
"_id": "5ecee2189fdd1b0004056936",
"name": "Mike",
"history": {
"_id": "5ecb263c166b8500047c1411",
"what": "Log IN"
},
"historyIndex": 0
},
{
"_id": "5ecee2189fdd1b0004056936",
"name": "Mike",
"history": {
"_id": "5ecb263c166b8500047c1422",
"what": "Log OUT"
},
"historyIndex": 1
}
]
}
用户文档
在现实生活中,将会有更多的用户。。。当然
{
"_id": "5ecee2189fdd1b0004056936",
"name": "Mike",
}
历史文件
同样,为了简单起见,我保持数据简短
[
{
"_id": "5ecb263c166b8500047c1411",
"userId": "5ecee2189fdd1b0004056936",
"what": "Log IN"
},
{
"_id": "5ecb263c166b8500047c1422",
"userId": "5ecee2189fdd1b0004056999",
"what": "Log IN"
},
{
"_id": "5ecb263c166b8500047c1433",
"userId": "5ecee2189fdd1b0004056936",
"what": "Log OUT"
},
{
"_id": "5ecb263c166b8500047c1444",
"userId": "5ecee2189fdd1b0004056999",
"what": "Log OUT"
}
]
mongoose-aggregate-paginate-v2中间件
我也在使用mongoose-aggregate-paginate-v2,但我不认为这是我的问题,但当返回结果时,它肯定会起作用。它需要将文档展平,以便对其进行计数和分页:
"totalDocs": 941,
"limit": 500,
"page": 1,
"totalPages": 2,
"pagingCounter": 1,
"hasPrevPage": false,
"hasNextPage": true,
"prevPage": null,
"nextPage": 2
管道
这是我的管道
var agg_match = {
$match:
{
_id: mongoose.Types.ObjectId(userId)
}
};
var agg_lookup = {
$lookup: {
from: 'it_userhistories',
localField: '_id',
foreignField: 'userId',
as: 'history'
}
}
var agg_unwind = {
$unwind: {
path: "$history",
preserveNullAndEmptyArrays: true,
includeArrayIndex: 'historyIndex',
}
}
var agg = [
agg_match,
agg_lookup,
agg_unwind,
agg_project,
];
var pageAndLimit = {
page:page,
limit:limit
}
User.aggregatePaginate(myAggregate, pageAndLimit)
您可以使用运算符来执行此操作。以下查询将非常有用(我没有在管道中包括匹配阶段,您可以轻松地将其包括在内):
db.user.aggregate([
{
$lookup:{
来自:“历史”,
localField:“\u id”,
foreignField:“用户ID”,
as:“历史”
}
},
{
$项目:{
姓名:1,,
历史:{
$map:{
输入:“$history”,
作为:“h”,
在:{
_id:“$$h.\U id”,
什么:“$$h.what”
}
}
}
}
}
])
完美!非常感谢。我的问题怎么样?可以理解吗?如果可以的话,你能给它投票吗?谢谢