In MongoDB, you can use JSON-style objects such as in the following to query a collection:
db.things.find({ x : { $ne : 3 }, y : 'foo' });
I'd like to reuse that { x : { $ne : 3 }, y : 'foo' }
bit and use it to filter an array of JavaScript objects.
Is there any code/library out there that can do that, and that supports all the query options (or as much as makes sense anyway)?
Ok, so here's another try:
sift.js (npm: sift) by Craig Condon is a MongoDB-inspired array
filtering library. It’s a bit like an alternative to Underscore for
people who love MongoDB. Sift.js supports operators like $in and $gt,
but can also filter arrays based on functions and even works with
deeply-nested objects in arrays.
Craig has provided a few examples that should look familiar to Mongo
users:
var sift = require('sift');
sift({ $in: ['hello','world'] }, ['hello','sifted','array!']); //
['hello']
Source: http://dailyjs.com/2012/01/04/node-roundup/
As far as I can see, Mingo has wider Mongo queries support than Sift.
Underscore.js is a great library to do map/reduce kind of jobs on javascript structures. Highly recommended.
I dont think you can just use the mongodb filters in normal js arrays. Because you need to understand the fact that
The filters specified in mongodb are evaluated in
mongodb indexes not in the javascript result set
Means the filters evaluated(translated) to query against a index not the js. So what you are asking is a DSL on top of mongodb(or JS) which will evaluate the mongodb index filters in the JS array.
I dont think its needed since both serves the different purposes (Though its possible(difficult) to write custom DSL). Also there are major frameworks like underscore.js already provide a ways to handle these.
You can use https://github.com/mirek/node-json-criteria library, which evaluates critera queries in MongoDB format on JSON objects.