Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Variables to a MongoDB View

Tags:

mongodb

i'm trying to make views in MongoDB to avoid unnecessary returns. In the documentation says that the aggregation functions can take variables with a double dollar sign, taking this in mind i have created a view that in this example should take one variable to filter customerIds and group the results to sum the payments of different documents.

Example:

db.createView(
  "viewName",
  "myCollection",
  [{
    $match: {  "customerId": "$$customerId", }
  },{
    $group: {
      _id: null,
      total: "$amount",
    }
  }]
)

The view is created OK and if i put some valid customerId in the aggregation function that works ok, but i don't have the slightest idea how to execute the view and pass the customerID that i need.

Any ideas? The mongodb documentation does not help me in this situation and i really need to create this as a view, since there are many applications that will connect to this view(s).

I have tried: db.viewName.find({customerId: "some valid id"});

like image 365
Hugazo Avatar asked Oct 12 '18 20:10

Hugazo


People also ask

How do I update a view in MongoDB?

To modify a view, you can either: Drop and recreate the view. Use the collMod command.

Can we create index on view in MongoDB?

Views use the indexes of the underlying collection. As the indexes are on the underlying collection, you cannot create, drop or re-build indexes on the view directly nor get a list of indexes on the view.

How do I declare a variable in MongoDB?

To assign a variable, specify a string for the variable name and assign a valid expression for the value. The variable assignments have no meaning outside the in expression, not even within the vars block itself.

What is $$ root?

$$ROOT. The $$ROOT variable contains the source documents for the group. If you'd like to just pass them through unmodified, you can do this by $pushing $$ROOT into the output from the group.


1 Answers

You can access it just like a collection, for example I am creating a view via:

db.runCommand({
  create: 'AuthorsView',
  viewOn: 'authors',
  pipeline: [{
    "$group": {
      "_id": "$email",
      "count": {
        "$sum": 1
      }
    }
  }]
})

Since this is now an existing view I can simply do:

db.getCollection('AuthorsView').find({})

To see all the documents or to add more parameters to the find

Not sure what you mean by passing variables since views are just like collections ... you run queries against them via find & aggregate.

like image 95
Akrion Avatar answered Oct 24 '22 10:10

Akrion