mongodb - mongodb 查询中键的通配符

标签 mongodb mongodb-query

我有一个相当于以下内容的集合:

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

将检索这两个文档。

最佳答案

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

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

关于mongodb - mongodb 查询中键的通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65783545/

相关文章:

c# - C# 中的 MongoDB 地理空间索引

ArchLinux中Mongodb无法导出数据

mysql - mongodb - 寻找类似于 mysql 的 "id in(1,2,3,4)"的选择查询

mongodb - $let 如何访问在其 mongoDB 表达式之外定义的变量?

MongoDB 2.6 服务器对低于限制的查询抛出 'BSONObj size is invalid' 错误

MongoDB 聚合管道组

node.js - Mongoose 返回不一致的结果

mongodb - 查找数组中共享相同值的所有文档

Mongodb查询项目

c# - 如何优化大型数据集上的 C# mongodb 查询?