Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 667
emertechie Avatar asked Jan 01 '12 21:01

emertechie


People also ask

How do I filter an array in MongoDB?

Filter MongoDB Array Element Using $Filter Operator This operator uses three variables: input – This represents the array that we want to extract. cond – This represents the set of conditions that must be met. as – This optional field contains a name for the variable that represent each element of the input array.

How you can query arrays in MongoDB?

To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }

How do I query an array of objects in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.

Does MongoDB work with JavaScript?

Although these methods use JavaScript, most interactions with MongoDB do not use JavaScript but use an idiomatic driver in the language of the interacting application. If you do not need to perform server-side execution of JavaScript code, see Disable Server-Side Execution of JavaScript.


3 Answers

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

like image 128
Emil Stenström Avatar answered Nov 15 '22 18:11

Emil Stenström


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

like image 37
Karol Selak Avatar answered Nov 15 '22 19:11

Karol Selak


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

like image 42
Mirek Rusin Avatar answered Nov 15 '22 19:11

Mirek Rusin