==编辑==
DB的初始记录:
[{ _id: 100,
ca : 12,
st : 0,
tranhisRev: [
{
uid : 1,
et: 2018-02-08T11:28:53.745Z },
{
uid : 2,
et: 2018-02-08T11:28:55.745Z },
{
uid : 3,
et: 2018-02-07T10:56:05.993Z },
{
uid : 4,
et: 2018-02-07T10:56:08.927Z },
{
uid : 1,
et: 2018-02-06T10:55:57.094Z },
{
uid : 2,
et: 2018-02-06T10:59:57.094Z }
]},
{ _id: 101,
ca : 19,
st : 1,
tranhisRev: [
{
uid : 1,
et: 2018-02-08T11:28:53.745Z },
{
uid : 2,
et: 2018-02-08T11:28:55.745Z },
{
uid : 3,
et: 2018-02-07T10:56:05.993Z },
{
uid : 4,
et: 2018-02-07T10:56:08.927Z },
{
uid : 1,
et: 2018-02-06T10:55:57.094Z },
{
uid : 2,
et: 2018-02-06T10:59:57.094Z }
]}
]
我想获得每个日期的最后记录,即第6个feb,第7个feb和第8个feb以及每个'_id'。
期望的结果是:
[
{ _id: 100,
ca : 12,
st : 0,
tranhisRev:
{
uid : 1,
et: 2018-02-08T11:28:55.745Z } },
{ _id: 100,
ca : 12,
st : 0,
tranhisRev:
{
uid : 4,
et: 2018-02-07T10:56:08.927Z } },
{ _id: 100,
ca : 12,
st : 0,
tranhisRev:
{
uid : 2,
et: 2018-02-06T10:59:57.094Z} },
{ _id: 101,
ca : 19,
st : 1,
tranhisRev:
{
uid : 2,
et: 2018-02-08T11:28:55.745Z } },
{ _id: 101,
ca : 19,
st : 1,
tranhisRev:
{
et: 2018-02-07T10:56:05.927Z } },
{ _id: 101,
ca : 19,
st : 1,
tranhisRev:
{
uid : 2,
et: 2018-02-06T10:59:57.094Z } }]
我尝试过使用
$group:
{
_id: "$_id",
tranhisRev: {$first: "$tranhisRev"}
}
但是没有帮助我,每个_id
都有一条记录。
$redact
我尝试过使用,但也没有帮助我。
$redact
会有所帮助。但问题是我必须获得多个日期的记录。
有人可以指导我如何实现这一目标吗?
任何现有的问题链接也会有所帮助。
答案 0 :(得分:1)
“每个ID的每一天”表示您需要按两个值进行分组,即在分组_id中包含day和_id:
db.collection.aggregate([
{ $unwind: "$tranhisRev" },
{ $group: {
_id: {
id: "$_id",
day: { $dateToString: { format:"%Y-%m-%d", date:"$tranhisRev.et" } }
},
et:{ $max:"$tranhisRev.et" }
} }
])