db.createView() in mongodb

createView(view, source, pipeline, options?)

This method creates a view as the result of applying the specified aggregation pipeline to the source collection or view. Views act as read-only collections and are computed on demand during reading operations.

MongoDB executes read operations on views as part of the underlying aggregation pipeline.


The following operation creates a "viewName" view with the _id, data1, and data2 fields:


db.createView(

  "viewName",

  "survey",

  [ { $project: {

    data1: "$value",

    dat2: 1  } } ]

)



Approach 1: When the view with the given name does not exist

MongoDB

db.createView(
        "view",
        "survey",
        [ { $project: {
          data1: "$value",
          data2: 1  } } ]
      )

Output:

{ "ok" : 1 }


Approach 2: View with the given name already exist

MongoDB

db.createView(
        "view",
        "survey",
        [ { $project: {
          data1: "$value",
          data2: 1  } } ]
      )

Output

{ "ok" : 0, "errmsg" : "Namespace already exists", "code" : 48, "codeName" : "NamespaceExists" }


No comments:

Post a Comment