【问题标题】:using $gte and $lt for picking different rages of a specific field value使用 $gte 和 $lt 来选择特定字段值的不同范围
【发布时间】:2022-01-11 23:03:31
【问题描述】:

我正在尝试选择成本字段在 0 到 5 之间的文档,然后尝试选择成本范围在 10 到 15 之间的文档。为此,我使用MongoDB aggregation

    const something = await dummyModel.aggregate([
      {
        $match: {
          fieldA: {
            $in: arryOfIds,
          },
          cost: {
            $or: [
              { $gte: 0, $lt: 5 },
              { $gte: 10, $lt: 15 },
            ],
          },
        },
      },
    ]);

通过上述方法,我从猫鼬那里得到了这个错误。

"message": "unknown operator: $or",

关于使用mongooseMongoDB 中选择范围的任何想法

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    您应该使用 find 查询。

    db.collection.find({
      "fieldA": {
        "$in": arryOfIds,
      },
      "$or": [
        {
          "cost": {
            "$gte": 0,
            "$lt": 5
          }
        },
        {
          "cost": {
            "$gte": 10,
            "$lt": 15
          }
        }
      ]
    })
    

    Working example

    【讨论】:

    • 对于和我情况相同的其他人,这个解决方案也适用于聚合管道内部。坦克你,省了很多力气;)
    猜你喜欢
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多