MongoDB 查询以查找列的最高数值?
为此,您可以将$not运算符与$type一起使用。让我们首先创建一个包含文档的集合-
> db.highestNumericValueOfAColumnDemo.insertOne(
... {
... "StudentName": "John",
... "StudentMathMarks":69
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cba05727219729fde21ddb1")
}
> db.highestNumericValueOfAColumnDemo.insertOne(
... {
... "StudentName": "Carol",
... "StudentMathMarks":"89"
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cba059d7219729fde21ddb2")
}
> db.highestNumericValueOfAColumnDemo.insertOne(
... {
... "StudentName": "Chris",
... "StudentMathMarks":82
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cba059d7219729fde21ddb3")
}
> db.highestNumericValueOfAColumnDemo.insertOne(
... {
... "StudentName": "John",
... "StudentMathMarks":"100"
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cba059d7219729fde21ddb4")
}以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.highestNumericValueOfAColumnDemo.find().pretty();
这将产生以下输出-
{
"_id" : ObjectId("5cba05727219729fde21ddb1"),
"StudentName" : "John",
"StudentMathMarks" : 69
}
{
"_id" : ObjectId("5cba059d7219729fde21ddb2"),
"StudentName" : "Carol",
"StudentMathMarks" : "89"
}
{
"_id" : ObjectId("5cba059d7219729fde21ddb3"),
"StudentName" : "Chris",
"StudentMathMarks" : 82
}
{
"_id" : ObjectId("5cba059d7219729fde21ddb4"),
"StudentName" : "John",
"StudentMathMarks" : "100"
}以下是查找列的最高数值的查询-
> db.highestNumericValueOfAColumnDemo.find({StudentMathMarks: {$not: {$type:
2}}}).sort({StudentMathMarks: -1}).limit(1).pretty();这将产生以下输出-
{
"_id" : ObjectId("5cba059d7219729fde21ddb3"),
"StudentName" : "Chris",
"StudentMathMarks" : 82
}上面的查询忽略了字符串值,所以我们只得到整数最大值82。