mongodb 在Nodejs和Mongoose中查找两个给定值之间的数据

2wnc66cl  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(150)

我试图在两个给定的高度之间查找数据。我将高度数据存储在单独的Mongodb模式中,其中高度的唯一_id是我存储在user-schema中的内容。因此,我在GET API中填充了()。
问题是当我在过滤器API上工作时,比如根据给定的两个高度查找用户,我怎样才能找到两个输入高度之间的用户数据?我应该通过两个高度_id来查找吗?如果是这样,我可以知道方法或一些建议或原始数据,如5.1到6?如果我通过原始数据,如5.1和5。8但我将如何找到用户数据,因为我没有在user-schema中存储原始数据,而是存储高度的id。

配置方案

const appconfigSchema = mongoose.Schema({
    configValue: {
        type: String,
        required: true,
    },
    configDesc: {
        type: String,
    },
...

配置示例数据

[
        {
            "_id": "636261302187d07f920b1174",
            "configValue": "5.1",
            "configDesc": "5ft 1in",
            "metaDataType": "Height",
            "isParent": false,
            "parentPrimaryId": "636260f82187d07f920b1171",
            "isActive": true,
            "createdAt": "2022-11-02T12:23:12.999Z",
            "updatedAt": "2022-11-02T12:23:12.999Z",
            "__v": 0
        }
    ]

用户方案

...
Height: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'appconfigs'
    },
...

用户示例数据

...
    "Country": "India",
    "State": "Tamil Nadu",
    "City": "Trichy",
    "Height": "636261302187d07f920b1174",
...

那么如何找到两个给定高度之间的用户数据?我应该只传递高度Id还是像5.1和5.8这样的高度原始数据,如果是这样,请教我方法

mspsb9vt

mspsb9vt1#

您可以使用Config mongoose DAO中的aggregate方法来执行一个如下所示的查询:

const heightValues = await Config.aggregate([
  // Step 1 - Filter "Height" metaDataType
  {$match: {metaDataType: "Height"}},
  // Step 2 - Cast their values to double
  {$project: {heightValue: {$toDouble: "$configValue"}}},
  // Step 3 - Filter with number values (here, x > 5 and x < 5.8)
  {$match: {heightValue: {$gte: 5, $lte: 5.8}}},
  // Step 4 - Fetch the users having "Height" foreign key equal to "_id" local key
  {$lookup: {
    from: "users",
    localField: "_id",
    foreignField: "Height",
    as: "users"
  }}
])

// Expected output

[
  {
    "_id": "636261302187d07f920b1174",
    "heightValue": 5.1,
    "users": [
      {
        "City": "Trichy",
        "Country": "India",
        "Height": "636261302187d07f920b1174",
        "State": "Tamil Nadu",
        "_id": ObjectId("5a934e000102030405000004"),
      }
    ]
  },
  ...
]

相关问题