In mongo I can construct a query like below to return objects with height not equal to 4 from a collection.
var mongoQuery = { height: { "$ne": 4 } };
But say I have an in-memory array of objects and want to query from them the same way:
var myArr = [{height: 5}, {height: 4}, {height:3}]
Are there any existing libraries or ways for me to use similar syntax on arrays instead of mongo collections? E.g.:
var result = someUtil(myArr, {height: {"$ne": 4}}); //returns all objects with height != 4
EDIT: I don't want to do != 4
, but rather generally translate from any Mongo operator (e.g. $eq
, $ge
, etc.)
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.
One of the benefits of MongoDB's rich schema model is the ability to store arrays as document field values. Storing arrays as field values allows you to model one-to-many or many-to-many relationships in a single document, instead of across separate collections as you might in a relational database.
The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. If you specify only a single <query> condition in the $elemMatch expression, and are not using the $not or $ne operators inside of $elemMatch , $elemMatch can be omitted.
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.
Please take a look at sift.js. That is what you want. But use it if you really need mongodb like queries, otherwise use another library like lodash or underscore.
Checkout underscore library.
var result = _.find(myArr, function(item){ return item.height == 4 });
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