Mongodb Aggregate with natural order

Viewed 922

I am looking for a way to query database to fetch last saved entry in the collection. I have a function which saves the document to the collection this is hwo my saved collection looks like.

{
  "_id": {
    "$oid": "5ebbf2b4586b4946226e2c88"
  },
  "name": "Stept_1",
  "description": "",
  "coordinates": {
    "pose": {
      "$numberInt": "0"
    },
    "x": {
      "$numberDouble": "-9.760518723445719"
    },
    "y": {
      "$numberDouble": "-3.4586615766853854"
    },
    "z": {
      "$numberInt": "0"
    }
  },
  "depth": {
    "$numberInt": "1"
  },
  "_neighbours": [],
  "optional": {},
  "__v": {
    "$Reference": "1111111"
  }
}

Each document is saved with name in ascending order e.g. name:Step_1, Step_2 etc. I have tried fetching the last saved documents using aggregate method like

db.collection.aggregate([
      { $sort: { name: -1 } },
      { $group: { _id: "$Reference", name: { $first: "$name" } } }
    ])

This returns the data in ascending order till name:Step_10 i.e. "Step_1,2,3,..." but once after name:Step_1o if I restart the app and again start fetching the last saved document the index of ascending order returns to name:Step_9 which then lead some duplicate entries of few documents. What I am looking for is it should always return follow natural order(i.e. Step_1,2,3,..11,12,13 etc) while fetching those documents. Thanks in advance.

1 Answers

You can use collation to specify numericOrdering like so:

db.collection.aggregate([
      { $sort: { name: -1 } },
      { $group: { _id: "$Reference", name: { $first: "$name" } } }
    ], 
    { collation : { 
        locale: "en_US", 
        numericOrdering: true 
    }} 
)

From mongo docs:

numericOrdering boolean Optional. Flag that determines whether to compare numeric strings as numbers or as strings.

If true, compare as numbers; i.e. "10" is greater than "2".

If false, compare as strings; i.e. "10" is less than "2".

Default is false.

Related