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"});
To modify a view, you can either: Drop and recreate the view. Use the collMod command.
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.
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.
$$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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With