【问题标题】:MongoDB add matched key to list after queryMongoDB在查询后将匹配的键添加到列表中
【发布时间】:2020-04-17 20:26:53
【问题描述】:

我在 MongoDB 中有一个包含嵌入式文档列表的文档。让我们举一个带有轮胎列表的汽车文档的简化示例:

{
    "make": "Toyota",
    "color": "blue",
    "tires": [{
        "make": "Mishlen",
        "size": 185
    }, {
        "make": "Mishlen",
        "size": 210
    }]
}

当我运行以下查询以查找轮胎尺寸低于 200 的所有汽车时,我得到了相同的文档,但我不知道哪个轮胎与查询匹配。

{"tires.size": {$gt: 200}}

我正在尝试返回某种结果:

{
    "make": "Toyota",
    "color": "blue",
    "tires": [{
        "make": "Mishlen",
        "size": 185,
        "matched": true
    }, {
        "make": "Mishlen",
        "size": 210,
        "matched": false
    }]
}

这样我就可以知道哪些轮胎符合我的查询。实现这种结果的最佳方法是什么?在性能方面。

【问题讨论】:

  • 添加您的查询情况
  • 添加什么?你能解释一下吗?
  • “当我运行查询以查找所有汽车时...” ..您的查询如何?
  • 建议的解决方案只返回列表和 id 而不是整个文档。我想收到带有过滤列表的整个文档或带有完整列表和额外字段的整个文档(在我的帖子中列出建议的回报)。我希望这是有道理的

标签: python mongodb mongoengine


【解决方案1】:

请试试这个:

db.yourCollectionName.aggregate([
    { $addFields: {
        tires: {$filter: {
            input: '$tires',
            as: 'each',
            cond: {$lt: ['$$each.size', 200]}
        }}
    }}
])

收集数据:

{
    "make": "Toyota",
    "color": "blue",
    "tires": [{
        "make": "Mishlen",
        "size": 185
    }, {
        "make": "Mishlen",
        "size": 210
    }]
}

结果:

{
    "make": "Toyota",
    "color": "blue",
    "tires": [{
        "make": "Mishlen",
        "size": 185
    }]
}

参考: $addFields , $filter

【讨论】:

    【解决方案2】:

    您可以使用$cond (aggregation) 添加新的布尔值。

    db.collection.aggregate([
      {
        $addFields: {
          tires: {
            $map: {
              input: "$tires",
              in: {
                make: "$$this.make",
                size: "$$this.size",
                matched: {
                  $cond: {
                    if: {
                      $lt: [
                        "$$this.size",
                        200
                      ]
                    },
                    then: true,
                    else: false
                  }
                }
              }
            }
          }
        }
      }
    ])
    

    结果:

    [
      {
        "color": "blue",
        "make": "Toyota",
        "tires": [
          {
            "make": "Mishlen",
            "matched": true,
            "size": 185
          },
          {
            "make": "Mishlen",
            "matched": false,
            "size": 210
          }
        ]
      }
    ]
    

    现场演示:MongoPlayground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-25
      • 2019-04-25
      • 2017-06-17
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      相关资源
      最近更新 更多