如何在 mongodb 中对嵌套值使用投影

How to use projection for nested value in mongod

如何使用投影仅查看集合中所有文档的以下部分?

条件: 我只需要获取“type”:“DEBIT”和以下 2 行,而不是同一类型的所有其他键。 我不想查看其他类型,例如帐户、存款。

{
     "key": "Call",
     "enabled": true,
 }

我在以下结构中的示例文档。

{
    "_id": "1",
    "menu": [
        {
            "type": "ACCOUNT",
            "scope": "ACCOUNT",
            "items": [
                {
                    "key": "Call",
                    "enabled": true,
                },
                {
                    "key": "Work",
                    "enabled": true,
                }
            ]
        },
        {
            "type": "DEPOSIT",
            "scope": "DEPOSIT",
            "items": [
               {
                    "key": "Call",
                    "enabled": true,
                },
                {
                    "key": "Work",
                    "enabled": true,
                }
            ]
        },
        {
            "type": "DEBIT",
            "scope": "DEBIT",
            "items": [
               {
                    "key": "Call",
                    "enabled": true,
                },
                {
                    "key": "Work",
                    "enabled": true,
                }
            ]
        },
    ]
}

使用$filter

db.collection.aggregate([
  {
    "$match": {
      "menu.type": "DEBIT"
    }
  },
  {
    "$set": {
      "menu": {
        "$filter": {
          "input": "$menu",
          "as": "m",
          "cond": {
            $eq: [
              "$$m.type",
              "DEBIT"
            ]
          }
        }
      }
    }
  }
])

mongoplayground

首先,您需要$unwind菜单 然后 $match 类型借方 并过滤数组项,然后分组以创建最终结果

db.collection.aggregate([
  {
    "$unwind": "$menu"
  },
  {
    $match: {
      "menu.type": "DEBIT"
    }
  },
  {
    "$project": {
      _id: 1,
      "menu.items": {
        "$filter": {
          "input": "$menu.items",
          "as": "s",
          "cond": {
            $and: [
              {
                $eq: [
                  "$$s.enabled",
                  true
                ]
              },
              {
                $eq: [
                  "$$s.key",
                  "Call"
                ]
              }
            ]
          }
        }
      }
    }
  },
  {
    "$group": {
      "_id": "$_id",
      "menu": {
        "$push": "$menu"
      }
    }
  }
])

https://mongoplayground.net/p/kRChgF9rLsI