简体   繁体   English

MongoDB:如何通过舍入特定字段来查询文档

[英]MongoDB: How to query documents by rounding a specific field

Let's suppose there is the following collection of documents in MongoDB:假设 MongoDB 中有以下文档集合:

Scores

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

I would like to query documents with the rounded value of 3 .我想查询四舍五入value 3文档。 So it will return { _id: 1, value: 3.25 } and { _id: 4, value: 2.5 } only.所以它只会返回{ _id: 1, value: 3.25 }{ _id: 4, value: 2.5 }

The Node.js query would be something like db.collection('scores').find({...}) Node.js 查询类似于db.collection('scores').find({...})

What do I need to put in the query?我需要在查询中输入什么?

I am not sure it possible to directly using any query operators,我不确定是否可以直接使用任何查询运算符,

you can prepare condition on the client-side by number's minimum and maximum value boundry, just prepare a function like,您可以通过数字的最小值和最大值边界在客户端准备条件,只需准备一个函数,例如,

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

You query would be and get condition,您查询将是并获得条件,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM