首页 > 解决方案 > MongoDB:如何通过舍入特定字段来查询文档

问题描述

假设 MongoDB 中有以下文档集合:

Scores

{ _id: 1, value: 3.25 }
{ _id: 2, value: 1.37 }
{ _id: 3, value: 2.48 }
{ _id: 4, value: 2.5 }

我想查询带有四舍五入value的文档3。所以它只会{ _id: 1, value: 3.25 }返回{ _id: 4, value: 2.5 }

Node.js 查询类似于db.collection('scores').find({...})

我需要在查询中输入什么?

标签: node.jsmongodb

解决方案


我不确定是否可以直接使用任何查询运算符,

您可以通过数字的最小值和最大值边界在客户端准备条件,只需准备一个函数,例如,

function getValueCondition(n) {
  return { 
    $gte: Math.round(n) - 0.5, 
    $lt: Math.round(n) + 0.5
  };
}

你查询会得到条件,

let inputNumber = 3;
db.collection('scores').find({ 
  value: getValueCondition(inputNumber)
});

推荐阅读