是否可以查看 MongoDB 视图的管道定义?

Pet*_*erB 7 mongodb mongodb-query

几天前我创建了 MongoDB 视图。现在我想再看一遍。(我为创建视图而编写的查询)。是否可以?

我尝试使用 collmod 函数,db.runCommand( { collMod: 'viewName'})但它只是返回“确定”作为响应。

我一直在搜索它几个小时,但没有运气。

kev*_*adi 7

您可以使用该db.getCollectionInfos()方法。有关方法的详细说明,请参阅手册

例如:

> db.createView('testview', 'test', {$project: {a:1, b:1}})

> db.getCollectionInfos({name:'testview'})
[
  {
    "name": "testview",
    "type": "view",
    "options": {
      "viewOn": "test",
      "pipeline": [
        {
          "$project": {
            "a": 1,
            "b": 1
          }
        }
      ]
    },
    "info": {
      "readOnly": true
    }
  }
]
Run Code Online (Sandbox Code Playgroud)

视图定义显示在pipeline字段下。

请注意,您还可以过滤type: 'view'以显示数据库中所有视图的定义:

> db.getCollectionInfos({type:'view'})
[
  {
    "name": "testview",
    "type": "view",
    "options": {
      "viewOn": "test",
      "pipeline": [
        {
          "$project": {
            "a": 1,
            "b": 1
          }
        }
      ]
    },
    "info": {
      "readOnly": true
    }
  },
  {
    "name": "testview2",
    "type": "view",
    "options": {
      "viewOn": "test",
      "pipeline": [
        {
          "$group": {
            "_id": null,
            "count": {
              "$sum": 1
            }
          }
        }
      ]
    },
    "info": {
      "readOnly": true
    }
  }
]
Run Code Online (Sandbox Code Playgroud)