My primary goal is to create a view querying a sub-collection field using a variable.
I tried, first, to create a view using a variable but that didn’t work. So, next I tried a function and then accessing the function to return a record:
But no permutations of invoking the view returns any data. I think that’s because the $$ marker is for placeholder, or reserved, variables like $$NOW…
So, question is: How do I create a database view to query a collection using a value to be determined at run-time? Second part is: How is this object invoked successfully (returns data)?
I’d like to paraphrase to ensure I understand your question. You’d like to create a view or “variable query” that takes in a variable from the application. That variable replaces part of the query to return specific results. Am I correct in my understanding of your question?
Essentially, it sounds like you’re asking for a stored procedure. You’d like to pass a variable to the server and have it return a cursor. Unfortunately, MongoDB doesn’t currently support stored procedures.
Even so, views may be useful here. If the goal is to simplify a complex $match (or query) so the application is abstracted away from the complexity, writing a view will solve this. Have the view contain a single stage ($match) and include the constant part of your query. The application then queries the view with its own match stage containing the variable portion of the query, greatly simplifying the overall application logic.
functions do not work in terms of being able to pass in a variable value to be used as a query qualifier for the filter
views won’t work either for the same reason; the variable will not be parsed at run-time.
I’ve built the functionality programatically, but was wondering why my attempts (above) wouldn’t work. I was pretty sure I’d figured out why the view wouldn’t work (can’t use $$ to delineate a non-reserved word in a view) but I’ve no idea why the function wouldn’t work since I pulled that off an example in the mongo doc proper unless it’s b/c that kind of function only works in the mongo shell (client-side).