前言
数据库有一索引字段,ObjectId
与string
类型混用。
需要辨明sort后的排序关系。
输入
json
[{
"_id": {
"$oid": "e98799a7e181225ad5c87476"
}
},
{
"_id": {
"$oid": "e98799a7e181225ad5c87477"
}
},
{
"_id": {
"$oid": "e98799a7e181225ad5c87480"
}
},
{
"_id": "e98799a7e181225ad5c87476"
},
{
"_id": "e98799a7e181225ad5c87476ccd7fc61"
},
{
"_id": "e98799a7e181225ad5c87478"
},
{
"_id": "e98799a7e181225ad5c87479"
}]
结论1 混排
经过测试,ObjectId
与string
类型混用时,
使用Ascending排序,ObjectId
总是排在string
之后。
string
内部遵循字典序。
python
for doc in coll.find({}).sort("_id", pymongo.ASCENDING):
print(doc)
"""
{'_id': 'e98799a7e181225ad5c87476'}
{'_id': 'e98799a7e181225ad5c87476ccd7fc61'}
{'_id': 'e98799a7e181225ad5c87478'}
{'_id': 'e98799a7e181225ad5c87479'}
{'_id': ObjectId('e98799a7e181225ad5c87476')}
{'_id': ObjectId('e98799a7e181225ad5c87477')}
{'_id': ObjectId('e98799a7e181225ad5c87480')}
"""
结论2 条件比较
在mongo内部,给定string
作为比较条件时,只会和string
类型直接进行比较。
返回值中不再出现ObjectId
类型。
python
for doc in coll.find({'_id':{'$gt':'e98799a7e181225ad5c87476'}}).sort("_id", pymongo.ASCENDING):
print(doc)
"""
{'_id': 'e98799a7e181225ad5c87476ccd7fc61'}
{'_id': 'e98799a7e181225ad5c87478'}
{'_id': 'e98799a7e181225ad5c87479'}
"""
类似地,给定ObjectId
作为比较对象时,返回值中也只存在ObjectId
类型。
python
for doc in coll.find({'_id':{'$gt': ObjectId('e98799a7e181225ad5c87476')}}).sort("_id", pymongo.ASCENDING):
print(doc)
"""
{'_id': ObjectId('e98799a7e181225ad5c87477')}
{'_id': ObjectId('e98799a7e181225ad5c87480')}
"""
想选中指定类型只需要
python
for doc in coll.find({'_id':{'$type':'objectId'}}).sort("_id", pymongo.ASCENDING):
print(doc)
"""
{'_id': ObjectId('e98799a7e181225ad5c87476')}
{'_id': ObjectId('e98799a7e181225ad5c87477')}
{'_id': ObjectId('e98799a7e181225ad5c87480')}
"""
# or
for doc in coll.find({'_id':{'$type':'string'}}).sort("_id", pymongo.ASCENDING):
print(doc)
"""
{'_id': 'e98799a7e181225ad5c87476'}
{'_id': 'e98799a7e181225ad5c87476ccd7fc61'}
{'_id': 'e98799a7e181225ad5c87478'}
{'_id': 'e98799a7e181225ad5c87479'}
"""
联合查询
准确地使用 类型指定$type
+ 比较条件$gt
时可以获得返回值。
但如果$type
给定string
,$gt
给定ObjectId
就会返回空。
python
query = { '$and':[{'_id': {'$type': "string"}}, {'_id':{'$gt':'e98'}}]}
"""
{'_id': 'e98799a7e181225ad5c87476'}
{'_id': 'e98799a7e181225ad5c87476ccd7fc61'}
{'_id': 'e98799a7e181225ad5c87478'}
{'_id': 'e98799a7e181225ad5c87479'}
"""
# or
for doc in coll.find({ '$and':[{'_id': {'$type': "objectId"}}, {'_id':{'$gt':ObjectId('e98799a7e181225ad5c87476')}}]}).sort("_id", pymongo.ASCENDING):
print(doc)
"""
{'_id': ObjectId('e98799a7e181225ad5c87477')}
{'_id': ObjectId('e98799a7e181225ad5c87480')}
"""