【问题标题】:Wildcard for key in mongodb querymongodb查询中键的通配符
【发布时间】:2021-01-18 23:35:28
【问题描述】:

我有一个相当于:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "sides": {
      "0": {
        "dist": 100
      },
      "1": {
        "dist": 10
      }
    }
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "sides": {
      "0": {
        "dist": 100
      }
    }
  }
]

我想执行一个查询,返回具有嵌套在sides 中的任何键的任何文档具有具有特定值的键dist。比如:

db.collection.find({"sides.*.dist": 10})

这里* 充当通配符,任何键都可以代替它。

这将检索:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "sides": {
      "0": {
        "dist": 100
      },
      "1": {
        "dist": 10
      }
    }
  }
]

另一方面

db.collection.find({"sides.*.dist": 100})

将检索两个文档。

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    如果sides 字段是数组,则不需要以下歌曲和舞蹈...

    db.collection.find(
    {
        $expr: {
            $gt: [{
                $size: {
                    $filter: {
                        input: { $objectToArray: "$sides" },
                        as: "x",
                        cond: { $eq: ["$$x.v.dist", 10] }
                    }
                }
            }, 0]
        }
    })
    

    【讨论】:

      【解决方案2】:

      您可以使用this获取匹配元素

      db.collection.aggregate([
        {
          "$project": {
            "sides_array": {//Reshape the sides
              "$objectToArray": "$sides"
            }
          }
        },
        {//Denormalize to get more than one matches
          "$unwind": "$sides_array"
        },
        {
          "$match": {//Condition goes here
            "sides_array.v.dist": 10
          }
        },
        {
          "$group": {//Group the data back, after unwinding
            "_id": "$_id",
            "sides": {
              "$push": "$sides_array"
            }
          }
        },
        {
          "$project": {//Reshape the data
            "_id": 1,
            "sides": {
              "$arrayToObject": "$sides"
            }
          }
        }
      ])
      

      【讨论】:

        猜你喜欢
        • 2011-09-05
        • 2015-04-05
        • 1970-01-01
        • 2016-04-06
        • 1970-01-01
        • 1970-01-01
        • 2020-10-13
        • 1970-01-01
        相关资源
        最近更新 更多