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

后端 未结 5 689
独厮守ぢ
独厮守ぢ 2021-02-08 22:02

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\

相关标签:
5条回答
  • 2021-02-08 22:12

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

    0 讨论(0)
  • 2021-02-08 22:19

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

    0 讨论(0)
  • 2021-02-08 22:22

    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/

    0 讨论(0)
  • 2021-02-08 22:24

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

    0 讨论(0)
  • 2021-02-08 22:32

    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 讨论(0)
提交回复
热议问题