目标:我需要根据日期和时间提取帖子和分享并排序,然后将它们放在一个对象数组中
{
"_id": {
"$oid": "5919e1f8b1f75c2b1cb504ea"
},
"user": {
"$oid": "58deb7db5aac7a0011d7bdf4"
},
"likes": [],
"comments": [],
"posts": [
{
"p_Id": {
"$oid": "596b16b1c657d21d8048287d"
},
"Date": {
"$date": "2017-07-16T07:33:06.238Z"
}
},
{
"p_Id": {
"$oid": "596b3068183c4f24d853f228"
},
"Date": {
"$date": "2017-07-16T09:22:49.451Z"
}
}
],
"__v": 331,
"shares": [
{
"sh_Id": {
"$oid": "596b2d65d65e092778a41e31"
},
"Date": {
"$date": "2017-07-16T09:09:57.666Z"
}
},
{
"sh_Id": {
"$oid": "596b2d9e371b5c2194775c0d"
},
"Date": {
"$date": "2017-07-16T09:10:54.701Z"
}
}
]
}
期望的结果:
[ {
"p_Id": {
"$oid": "596b16b1c657d21d8048287d"
},
"Date": {
"$date": "2017-07-16T07:33:06.238Z"
}
},
{
"sh_Id": {
"$oid": "596b2d65d65e092778a41e31"
},
"Date": {
"$date": "2017-07-16T09:09:57.666Z"
}
},
{
"sh_Id": {
"$oid": "596b2d9e371b5c2194775c0d"
},
"Date": {
"$date": "2017-07-16T09:10:54.701Z"
}
},
{
"p_Id": {
"$oid": "596b3068183c4f24d853f228"
},
"Date": {
"$date": "2017-07-16T09:22:49.451Z"
}
},
{
"p_Id": {
"$oid": "596b3071183c4f24d853f229"
},
"Date": {
"$date": "2017-07-16T09:22:57.911Z"
}
}]
我的查询:
Activity.aggregate([
{ $match : { user : mongoose.Types.ObjectId(data.user) } },
{ $unwind: "$posts" }, { $unwind: "$shares"},
{ $project : { _id: 0, posts: 1, shares: 1 } }
]).exec(function(err,result){
console.log(result);
});
但是这个查询会成对出现结果。即在子文档中,每个共享发生相同的帖子。例如
我的结果:
[ { posts:
{ p_Id: 596b16b1c657d21d8048287d,
Date: 2017-07-16T07:33:06.214Z },
shares:
{ sh_Id: 596b2d65d65e092778a41e31,
Date: 2017-07-16T09:09:57.666Z } },
{ posts:
{ p_Id: 596b16b1c657d21d8048287d,
Date: 2017-07-16T07:33:06.214Z },
shares:
{ sh_Id: 596b2d9e371b5c2194775c0d,
Date: 2017-07-16T09:10:54.701Z } },
{ posts:
{ p_Id: 596b16b1c657d21d8048287d,
Date: 2017-07-16T07:33:06.214Z },
shares:
{ sh_Id: 596b30c1183c4f24d853f22c,
Date: 2017-07-16T09:24:17.621Z } }]