首页 > 解决方案 > 如何使用 match 子句匹配 mongo 中的嵌套字段?

问题描述

我正在尝试匹配 mongo 文档中的嵌套字段,但我的查询不起作用。

配置:

[
  {
    linenumber: "car",
    type: "004",
    nested: {
      info: {
        subinfo: "B"
      }
    },
    
  },
  {
    linenumber: "car",
    type: "005",
    nested: {
      info: {
        subinfo: "G"
      }
    },
    
  }
]

询问:

db.collection.aggregate([
  {
    $match: {
      $and: [
        {
          linenumber: "car"
        },
        {
          nested: {
            info: {
              subinfo: {
                $in: [
                  "B",
                  "G"
                ]
              }
            }
          }
        }
      ]
    }
  },
  {
    $group: {
      _id: null,
      types: {
        $addToSet: "$type"
      }
    }
  }
])

我正在使用 mongoplayground 进行测试。这是链接: https ://mongoplayground.net/p/nND59iO1339

我没有找到任何文件。

标签: mongodb

解决方案


你快到了。您需要使用点表示法。

db.collection.aggregate([
  {
    $match: {
      $and: [
        {
          linenumber: "car"
        },
        {
          "nested.info.subinfo": { //Dot notation
            $in: [
              "B",
              "G"
            ]
          }
        }
      ]
    }
  },
  {
    $group: {
      _id: null,
      types: {
        $addToSet: "$type"
      }
    }
  }
])

推荐阅读