Let me present the case first so that everyone can understand what I mean:
/a/1190000004157112
The above link is an ordinary sqlgroup query, but the problem I am encountering now is using mongo to perform group query
Aggregation query is really killing me. Here is the simulated data:
(Please forgive my data, he is uninhibited and free)
{
"_id" : ObjectId("590c15751f70bd329f8a972d"),
"_class" : "com.birdnest.model.AppPublish",
"user" : "admin",
"deviceType" : "nurse",
"version" : "1.1。2。2",
"message" : "范德萨312313213213范德萨",
"creation" : ISODate("2017-05-05T06:02:29.300Z")
}
{
"_id" : ObjectId("590c15751f70bd329f8a972e"),
"_class" : "com.birdnest.model.AppPublish",
"user" : "admin",
"deviceType" : "nurse",
"version" : "1.1。2。2",
"message" : "范德萨312313213213范德萨",
"creation" : ISODate("2017-05-05T06:02:29.447Z")
}
{
"_id" : ObjectId("590c157b1f70bd329f8a972f"),
"_class" : "com.birdnest.model.AppPublish",
"user" : "admin",
"deviceType" : "bed",
"version" : "1.1。2。2",
"message" : "范1123德萨312313213213范德萨",
"creation" : ISODate("2017-05-05T06:02:35.731Z")
}
{
"_id" : ObjectId("590c157c1f70bd329f8a9730"),
"_class" : "com.birdnest.model.AppPublish",
"user" : "admin",
"deviceType" : "bed",
"version" : "1.1。2。2",
"message" : "范1123德萨312313213213范德萨",
"creation" : ISODate("2017-05-05T06:02:36.164Z")
}
{
"_id" : ObjectId("590c158a1f70bd329f8a9733"),
"_class" : "com.birdnest.model.AppPublish",
"user" : "admin",
"deviceType" : "room",
"version" : "1.1.112",
"message" : "范1123德萨312313213213范德萨",
"creation" : ISODate("2017-05-05T06:02:50.082Z")
}
{
"_id" : ObjectId("590c158a1f70bd329f8a9734"),
"_class" : "com.birdnest.model.AppPublish",
"user" : "admin",
"deviceType" : "room",
"version" : "1.1.112",
"message" : "范1123德萨312313213213范德萨",
"creation" : ISODate("2017-05-05T06:02:50.238Z")
}
The requirements are like this
According to the deviceType classification, get the latest version number of each category
The result I want is like this
/* 1 */
{
"deviceType" : "bed",
"version" :"1.1.112")
}
/* 2 */
{
"deviceType" : "room",
"version" :"1.1.112")
}
/* 3 */
{
"deviceType" : "nurse",
"version" : "1.1.112")
}
The following statement was written by myself, but there are many problems
Although the thing I wrote was done, the desired result could not be displayed
db.appPublish.aggregate(
{$group : {_id :"$deviceType",creation : {$max : "$creation"}}}
);
1._id cannot be mapped to an object
2.version cannot be written in group
I really don’t understand this syntax
Result
/* 1 */
{
"_id" : "bed",
"creation" : ISODate("2017-05-05T06:02:44.750Z")
}
/* 2 */
{
"_id" : "room",
"creation" : ISODate("2017-05-05T06:02:50.397Z")
}
/* 3 */
{
"_id" : "nurse",
"creation" : ISODate("2017-05-05T06:02:29.447Z")
}
_id
当然映射不到真正的_id
上,这里的_id
指的是group
的key。不清楚你的
version
和creation
是什么关系,creation
比较大的文档version
It must be relatively new? If this condition is true, you can do this:$first
即group
之后取第一个元素。而事先已经按creation
In order, so the first one is the newest element.