首页 > 解决方案 > mongodb查询中键的通配符

问题描述

我有一个相当于:

[
  {
    "_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})

将检索两个文件。

标签: mongodbmongodb-query

解决方案


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

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"
      }
    }
  }
])

推荐阅读