Home > OS >  Find last inserted document for a given field
Find last inserted document for a given field

Time:07-29

Using Go driver for Mongo, I have a simple collection, each document is my last visit to the city. How to find all documents, most recent visit to field destination. Field _id is auto-generated and incrementing chronologically.

[
  {
    "_id": "62e0d290fd1a769bb8ad13ba",
    "destination": "NY"
    "airline": "Delta"
  },
  {
    "_id": "62e0d2defd1a769bb8ad13bb",
    "destination": "DC"
    "airline": "Southwest"
  },
  {
    "_id": "62e0d2defd1a769bb8ad13bc",
    "destination": "DC"
    "airline": "American"
  {
    "_id": "62e0d2defd1a769bb8ad13bd",
    "destination": "NY"
    "airline": "JetBlue"
  }
]

Expected output (most recent inserted document for visit to each city)

[
  {
    "_id": "62e0d2defd1a769bb8ad13bc",
    "destination": "DC"
    "airline": "American"
  {
    "_id": "62e0d2defd1a769bb8ad13bd",
    "destination": "NY"
    "airline": "JetBlue"
  }
]

CodePudding user response:

Hope this answer will help to you

db.collection.aggregate([
  {
    "$group": {
      "_id": "$destination",
      "airline": {
        "$last": "$airline"
      },
      "destination": {
        "$last": "$destination"
      },
      "id": {
        "$last": "$_id"
      }
    }
  },
  {
    "$project": {
      _id: "$id",
      destination: 1,
      airline: 1
    }
  },
  {
    "$sort": {
      _id: 1,
      
    }
  }
])

enter image description here

  • Related