[Resolved ]mongodb Time Scheduling Problem

  mongodb, question

Business background

  • I want to sort by time.
  • Take the latest data

Difficulties encountered

  • March 2019 is always larger than April 2019
  • But normally, shouldn’t March be smaller than April?

Sample code

Ascending query

> db.getCollection("cash-infos").find({},{createdAt:1}).sort({createdAt: 1})
 
 {"_ id": objectid ("5caa78992f26e525a86085d2"), "createdat": "monapr08201906: 23: 46 gmt+0800 (china standard time)"}
 {"_ id": objectid ("5caa80e83de 43925c80353a7"), "createdat": "monapr08201906: 57: 37 gmt+0800 (china standard time)"}
 {"_ id": objectid ("5caa81723 de 43925c80353a8"), "created at": "monapr08 2019 06: 57: 37 GMT+0800 (China standard time)"}
 {"_ id": objectid ("5caa823491e61b3660367 fd2"), "createdat": "monapr082019 07: 05: 20 gmt+0800 (china standard time)"}
 {"_ id": objectid ("5caa8252d660a42d2cbb6bb2"), "createdat": "monapr082019 07: 05: 50 gmt+0800 (china standard time)"}
 {"_ id": objectid ("5caa82a4f0d94e34c4eecf46"), "createdat": "monapr08201907: 07: 12 gmt+0800 (china standard time)"}
 {"_ id": objectid ("5c7efc6b495b71617c42a9ce"), "created at": "wedmar 062019 06: 45: 39 GMT+0800 (China standard time)"}

Descending query

> db.getCollection("cash-infos").find({},{createdAt:1}).sort({createdAt: -1})
 
 {"_ id": objectid ("5c7efc6b495b71617c42a9ce"), "created at": "wedmar 062019 06: 45: 39 GMT+0800 (China standard time)"}
 {"_ id": objectid ("5caa82a4f0d94e34c4eecf46"), "createdat": "monapr08201907: 07: 12 gmt+0800 (china standard time)"}
 {"_ id": objectid ("5caa8252d660a42d2cbb6bb2"), "createdat": "monapr082019 07: 05: 50 gmt+0800 (china standard time)"}
 {"_ id": objectid ("5caa823491e61b3660367 fd2"), "createdat": "monapr082019 07: 05: 20 gmt+0800 (china standard time)"}
 {"_ id": objectid ("5caa80e83de 43925c80353a7"), "createdat": "monapr08201906: 57: 37 gmt+0800 (china standard time)"}
 {"_ id": objectid ("5caa81723 de 43925c80353a8"), "created at": "monapr08 2019 06: 57: 37 GMT+0800 (China standard time)"}
 {"_ id": objectid ("5caa78992f26e525a86085d2"), "createdat": "monapr08201906: 23: 46 gmt+0800 (china standard time)"}

This is a string. The string sorting is byte-by-byte. Of course, you cannot get the correct order. Change to date time type.