Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use mongo-style syntax to query in-memory JavaScript objects from arrays instead of Mongo collections?

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

like image 208
aspin Avatar asked Dec 03 '15 07:12

aspin


People also ask

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.

Can we store array of objects in MongoDB?

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.

How do I match an array in MongoDB?

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.

How do I filter an array element 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.


2 Answers

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.

like image 152
pablovilas Avatar answered Nov 13 '22 00:11

pablovilas


Checkout underscore library.

var result = _.find(myArr, function(item){ return item.height == 4 });

like image 40
AlexD Avatar answered Nov 13 '22 01:11

AlexD