10

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)?

emertechie
  • 3,607
  • 2
  • 22
  • 22

5 Answers5

11

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 (Edited): Daily JS, but seems site is down.

Emil Stenström
  • 13,329
  • 8
  • 53
  • 75
4

As far as I can see, Mingo has wider Mongo queries support than Sift.

Karol Selak
  • 4,248
  • 6
  • 35
  • 65
2

Underscore.js is a great library to do map/reduce kind of jobs on javascript structures. Highly recommended.

Emil Stenström
  • 13,329
  • 8
  • 53
  • 75
  • Those are also natively available in `Array.prototype` on more modern browsers. I think the OP is wanting to pass an object to filter the Mongo way (I guess including atomic operations like `$in`). – pimvdb Jan 01 '12 at 22:49
  • Correct, I want to be able to use the same filter to filter MongoDB data _and_ regular JavaScript arrays – emertechie Jan 02 '12 at 18:50
1

You can use https://github.com/mirek/node-json-criteria library, which evaluates critera queries in MongoDB format on JSON objects.

Mirek Rusin
  • 18,820
  • 3
  • 43
  • 36
-1

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.

RameshVel
  • 64,778
  • 30
  • 169
  • 213