最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Is there a way to use MongoDB query objects to filter regular JavaScript arrays? - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question edited Jan 2, 2012 at 18:48 emertechie asked Jan 1, 2012 at 21:36 emertechieemertechie 3,8473 gold badges25 silver badges22 bronze badges 1
  • 1 sounds like a good suggestion for the MongoDB folks to add to their library. – Jason S Commented Jan 2, 2012 at 19:03
Add a comment  | 

5 Answers 5

Reset to default 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.

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.

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

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.

发布评论

评论列表(0)

  1. 暂无评论