views:

52

answers:

1

I'm looking to write a function to do a custom query on a collection in Mongo. Problem is, I want to reuse that function. My thought was this (obviously contrived):

var awesome = function(count) {
  return function() {
    return this.size == parseInt(count);
  };
}

Executed that function in the Mongo console, and then proceeded to run this:

db.collection.find(awesome(5));

However, I get this error:

error: {
    "$err" : "error on invocation of $where function:
JS Error: ReferenceError: count is not defined nofile_b:1"
}

So, it looks like Mongo isn't honoring scope, but I'm really not sure why. Any insight would be appreciated.

To go into more depth of what I'd like to do:

A collection of documents has lat/lng values, and I want to find all documents within a concave or convex polygon. I have the function written but would ideally be able to reuse the function, so I want to pass in an array of points composing my polygon to the function I execute on Mongo's end. I've looked at Mongo's geospatial querying and it currently on supports circle and box queries - I need something more complex.

+1  A: 

You need to save that function to the database if you want to use it in a query. Do:

db.system.js.save({_id : "awesome", value : 
... function(count) { 
...     return this.size==count;
... }})
db.collection.find({"$where" : "awesome(5)"})

The shell isn't the database itself, so you can't define something in the shell and use it in the database, any more than you could define a variable in Python and expect the database to know about it.

kristina