【问题标题】:Mongodb find distinct value with rangeMongodb在范围内找到不同的值
【发布时间】:2020-09-05 12:51:04
【问题描述】:

我有一个 mongodb 数据库,其中有两个集合 - elementspropertieselements 看起来像这样 -

{ _id: "someElementId", name: "Iron", type: "metal" }

properties 看起来像这样 -

{ _id: "somePropertyId", propName: "molecular weight", propType: "number", unit: null }

每个element 可以有多个properties 和一个对应属性的值。例如iron 可以有属性molecular weightcoloratomic weight 等。

为此,我创建了另一个集合,其中存储了元素 ID 和相应的属性 ID 及其值 -

{ elementId: "someElementId", propId:  "somePropertyId", value: 55.845 }

现在我想查找数据库中出现的所有唯一属性的名称及其值的范围。因此,例如,如果 1 是与上述属性相对应的最低值,而 100 是最高值,我想要类似 -

[ { name: "molecular weight", range: { min: 1, max: 100 } } ]

我可以获取不同的属性并对其进行迭代以获取范围,但我想知道是否有更好的方法。还是这个表结构不够高效?

【问题讨论】:

    标签: database mongodb nosql aggregation-framework nosql-aggregation


    【解决方案1】:

    请检查这是否适合您:

    db.collection.aggregate([
      {
        $group: {
          _id: "$propId",
          min: {
            $min: "$value"
          },
          max: {
            $max: "$value"
          }
        }
      },
      {
        $lookup: {
          from: "properties",
          localField: "_id",
          foreignField: "_id",
          as: "name"
        }
      },
      {
        $unwind: "$name"
      },
      {
        $project: {
          _id: 0,
          "name": "$name.propName",
          "range": {
            "min": "$min",
            "max": "$max"
          }
        }
      }
    ])
    

    Mongo Playground

    【讨论】:

    • 谢谢。但我必须根据idproperties 集合中获取name 字段
    • 我现在明白了,我的错。我已经更新了答案,请看一下!
    猜你喜欢
    • 1970-01-01
    • 2020-11-23
    • 2021-06-18
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多