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)?
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.
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>, ... } }
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.
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.
Underscore.js is a great library to do map/reduce kind of jobs on javascript structures. Highly recommended.
As far as I can see, Mingo has wider Mongo queries support than Sift.
You can use https://github.com/mirek/node-json-criteria library, which evaluates critera queries in MongoDB format on JSON objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With