Mongoose排序并且每个字段只获得一个

时间:2018-06-14 16:07:13

标签: node.js mongodb 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

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以在mongodb中使用$group来区分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"
  }
]