something is wrong with my aggregation function. I get duplicate elements.
I try it with this: MongoDB sort documents by array elements
console.log('####');
console.log('offset', offset);
console.log('pageSize', pageSize);
ProcedureModel.aggregate([
{ $match: { 'history.initiator': '2. Beratung' } },
{
$addFields: {
order: {
$arrayElemAt: [
{
$filter: {
input: '$history',
as: 'p',
cond: { $eq: ['$$p.initiator', '2. Beratung'] },
},
},
0,
],
},
},
},
{ $sort: { 'order.date': -1 } },
{ $skip: offset },
{ $limit: pageSize },
]).then((res) => {
res.forEach((r, i) => console.log(`${i}: `, r._id));
return res;
});
My objects looks like this
{
"_id" : ObjectId("5a75a91ea57539646d00be29"),
"procedureId" : "81080",
"history" : [
{
"_id" : ObjectId("5a75a91d4a5aa5541db67598"),
"initiator" : "Änderung der Ausschussüberweisung",
"date" : ISODate("2017-06-01T00:00:00.000Z"),
},
{
"_id" : ObjectId("5a75a91d4a5aa5541db67597"),
"initiator" : "Beschlussempfehlung und Bericht, Urheber : Ausschuss für Recht und Verbraucherschutz",
"date" : ISODate("2017-06-28T00:00:00.000Z")
},
{
"_id" : ObjectId("5a75a91d4a5aa5541db67596"),
"initiator" : "2. Beratung",
"date" : ISODate("2017-06-30T00:00:00.000Z"),
…
},
…
],
…
}
and this is my result. there are two duplicate results :(
####
offset 0
pageSize 3
0: 5a75a91ea57539646d00be29
1: 5a75a91ea57539646d00bdb6
2: 5a75a91ea57539646d00bab7
####
offset 3
pageSize 3
0: 5a75a91ea57539646d00be65
1: 5a75a91ea57539646d00be29
2: 5a75a91ea57539646d00bab7
####
offset 6
pageSize 3
0: 5a75a91ea57539646d00b9eb
1: 5a75a91ea57539646d00bba5
2: 5a75a91ea57539646d00bb9f
why did have the second request two results of the first request, and the third none of the previous? and how I set up a correct offset and limit?
ProcedureModel.aggregate([ { $match: { 'history.initiator': '2. Beratung' } }]).exec((err, docs) => console.log(docs));