gpt4 book ai didi

Mongodb按数字排序

转载 作者:行者123 更新时间:2023-12-05 01:02:56 28 4
gpt4 key购买 nike

我正在尝试按包含数字的字段进行排序,当执行 .sort({title: 1}) 时,它将返回类似 1,10,11,12 的结果, 2,3,4。我想让它像 1,2,3,4,10,11,12 一样返回,这可以直接从 mongo 中返回吗?

最佳答案

例子:

db.test.find().sort({a:1})
{ "_id": ObjectId("60a018168823ff3bd585b308"), "a": "1" }
{ "_id": ObjectId("60a0181d8823ff3bd585b30a"), "a": "10" }
{ "_id": ObjectId("60a0181f8823ff3bd585b30b"), "a": "11" }
{ "_id": ObjectId("60a018198823ff3bd585b309"), "a": "2" }

使用排序规则和数字排序

db.test.find().sort({a:1}).collation({ locale: "en_US", numericOrdering: true }).ugly()
{ "_id": ObjectId("60a018168823ff3bd585b308"), "a": "1" }
{ "_id": ObjectId("60a018198823ff3bd585b309"), "a": "2" }
{ "_id": ObjectId("60a0181d8823ff3bd585b30a"), "a": "10" }
{ "_id": ObjectId("60a0181f8823ff3bd585b30b"), "a": "11" }

这个答案可以帮助按升序排序

db.collectionName.find()
.sort({sortingParameter: 1})
.collation({
locale: "en_US",
numericOrdering: true
})
from pymongo import MongoClient
from pymongo.collation import Collation

collectionName = MongoClient().testDB.collectionName

collectionName.find()
.sort('sortingParameter')
.collation(Collation(locale='en_US', numericOrdering=True))

关于Mongodb按数字排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24149105/

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