我是Mongo Db的新手,希望对此查询有所帮助。我的mongodb数据横断面相同id的数目基于create_date如何显示每个横断面id的第一记录
db.collection.aggregate([{
{"$project": {
"RESOURCE_ID": 1,
"TRANSACTION_ID":1,
"CREATE_DATE":1
}}
])
输出:
RESOURCE_ID TRANSACTION_ID CREATE_DATE
1 "100-101" "0:ffff0a0a0983UY:-142" "Fri Sep 07 16:51:30IST2018"
2 "100-101" "0:ffff0a0a0983UY:-142" "Fri Sep 07 16:51:29IST2018"
3 "100-101" "0:ffff0a0a0983UY:-142" "Fri Sep 07 16:51:29IST2018"
4 "100-102" "0:ffff0a0a0983UY:-111" "Fri Sep 06 16:51:29IST2018"
5 "100-102" "0:ffff0a0a0983UY:-111" "Fri Sep 06 16:51:28IST2018"
预期输出:
RESOURCE_ID TRANSACTION_ID CREATE_DATE
1 "100-101" "0:ffff0a0a0983UY:-142" "Fri Sep 07 16:51:30IST2018"
2 "100-102" "0:ffff0a0a0983UY:-111" "Fri Sep 06 16:51:29IST2018"
答案 0 :(得分:1)
这是您想要的:
onSingleTapConfirmed
它的作用-按日期升序对所有文档进行排序,因为我们首先需要最早的文档(请注意db.collection.aggregate([{"$sort": {CREATE_DATE: 1}},{$group:{"_id": "$RESOURCE_ID", TRANSACTION_ID: {$first: "$TRANSACTION_ID"}, "CREATE_DATE": {$first: "$CREATE_DATE"}}}])
子句)。
然后,它通过字段“ RESOURCE_ID”(标记为新的sort
)对文档进行分组,并使用_id
TRANSACTION_ID和$first
CREATE_DATE。
请注意,您必须将时间戳转换为实际时间戳,才能使mongo真正了解时间戳的顺序。否则mongo会将它们排序为字符串,这不是您想要的
一个例子:
$first
此外,值得一提的是,您应该为> db.collection.find().pretty()
{
"_id" : ObjectId("5bd2bf353ca22147747ec212"),
"RESOURCE_ID" : "100-101",
"TRANSACTION_ID" : "0:ffff0a0a0983UY:-142",
"CREATE_DATE" : ISODate("2017-10-13T10:53:53Z")
}
{
"_id" : ObjectId("5bd2bf3c3ca22147747ec213"),
"RESOURCE_ID" : "100-101",
"TRANSACTION_ID" : "0:ffff0a0a0983UY:-142",
"CREATE_DATE" : ISODate("2017-10-14T10:53:53Z")
}
{
"_id" : ObjectId("5bd2bf3c3ca22147747ec214"),
"RESOURCE_ID" : "100-102",
"TRANSACTION_ID" : "0:ffff0a0a0983UY:-111",
"CREATE_DATE" : ISODate("2017-10-13T10:53:53Z")
}
{
"_id" : ObjectId("5bd2bf3c3ca22147747ec215"),
"RESOURCE_ID" : "100-102",
"TRANSACTION_ID" : "0:ffff0a0a0983UY:-111",
"CREATE_DATE" : ISODate("2017-10-14T10:53:53Z")
}
> db.collection.aggregate([{"$sort": {CREATE_DATE: 1}},{$group:{"_id": "$RESOURCE_ID", TRANSACTION_ID: {$first: "$TRANSACTION_ID"}, "CREATE_DATE": {$first: "$CREATE_DATE"}}}])
{ "_id" : "100-102", "TRANSACTION_ID" : "0:ffff0a0a0983UY:-111", "CREATE_DATE" : ISODate("2017-10-13T10:53:53Z")
{ "_id" : "100-101", "TRANSACTION_ID" : "0:ffff0a0a0983UY:-142", "CREATE_DATE" : ISODate("2017-10-13T10:53:53Z")
添加索引,因为您要按此字段进行排序;而应该为CREATE_DATE
添加索引,因为mongo必须对其进行排序才能对其进行分组