gpt4 book ai didi

node.js - Mongoose 排序并每个字段只获取一个

转载 作者:太空宇宙 更新时间:2023-11-04 00:08:59 24 4
gpt4 key购买 nike

我需要使用 Mongoose 获取项目列表,但是,我只需要选择任何类型的一个项目(我有 5 个可能的值),并且始终是该类型的最后插入的项目。

例如,下面的列表,未订购(我知道,这里是订购的)。

[
{
"_id": "5b226abab64b2309de01bfd5",
"documentType": "type3",
"createdAt": "2018-06-14T13:16:42.321Z"
},
{
"_id": "5b226a5da93b0e09b8aee447",
"documentType": "type3",
"createdAt": "2018-06-14T13:15:09.458Z"
},
{
"_id": "5b226a21f454d6097ffa461c",
"documentType": "type2",
"createdAt": "2018-06-14T13:14:09.159Z"
},
{
"_id": "5b2267fb445d7709590e1695",
"documentType": "type1",
"createdAt": "2018-06-14T13:04:59.742Z"
},
{
"_id": "5b2267de76708b094696b0fe",
"documentType": "type3",
"createdAt": "2018-06-14T13:04:30.349Z"
},
{
"_id": "5b2267ce2f3724092b1a14a3",
"documentType": "type2",
"createdAt": "2018-06-14T13:04:14.410Z"
},
{
"_id": "5b2267a92f3724092b1a14a2",
"documentType": "type4",
"createdAt": "2018-06-14T13:03:37.079Z"
},
{
"_id": "5b22647b63017e08a69a3043",
"documentType": "type5",
"createdAt": "2018-06-14T12:50:03.999Z"
},
{
"_id": "5b2264471778a20880d4ba64",
"documentType": "type5",
"createdAt": "2018-06-14T12:49:11.773Z"
}
]

预期结果是这样的:

[
{
"_id": "5b226abab64b2309de01bfd5",
"documentType": "type3",
"createdAt": "2018-06-14T13:16:42.321Z"
},
{
"_id": "5b226a21f454d6097ffa461c",
"documentType": "type2",
"createdAt": "2018-06-14T13:14:09.159Z"
},
{
"_id": "5b2267fb445d7709590e1695",
"documentType": "type1",
"createdAt": "2018-06-14T13:04:59.742Z"
},
{
"_id": "5b2267a92f3724092b1a14a2",
"documentType": "type4",
"createdAt": "2018-06-14T13:03:37.079Z"
},
{
"_id": "5b22647b63017e08a69a3043",
"documentType": "type5",
"createdAt": "2018-06-14T12:50:03.999Z"
}
]

基本上每种类型只有一个,按 id 对 desc 进行排序

我该怎么做?

最佳答案

您可以使用$group通过在 mongodb 中区分 documentType

db.collection.aggregate([
{ "$group": {
"_id": "$documentType",
"createdAt": { "$first": "$createdAt" },
"id": { "$first": "$_id" }
}},
{ "$project": {
"_id": "$id",
"createdAt": 1,
"documentType": "$_id"
}}
])

输出将是

[
{
"_id": "5b226abab64b2309de01bfd5",
"createdAt": "2018-06-14T13:16:42.321Z",
"documentType": "type3"
},
{
"_id": "5b2267fb445d7709590e1695",
"createdAt": "2018-06-14T13:04:59.742Z",
"documentType": "type1"
},
{
"_id": "5b22647b63017e08a69a3043",
"createdAt": "2018-06-14T12:50:03.999Z",
"documentType": "type5"
},
{
"_id": "5b2267a92f3724092b1a14a2",
"createdAt": "2018-06-14T13:03:37.079Z",
"documentType": "type4"
},
{
"_id": "5b226a21f454d6097ffa461c",
"createdAt": "2018-06-14T13:14:09.159Z",
"documentType": "type2"
}
]

关于node.js - Mongoose 排序并每个字段只获取一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50861749/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com