Is it possible to fetch documents that match the conditions inside a JS function, something like:
db.getCollection("persons").find({"dob.age":{$eq:70} } ).forEach(function(doc) {
if(doc.registered.age == doc.dob.age*2){ //or some other complicated conditions
return doc;
}
});
The above code doesn't work but if it did I would expect it to return all documents where registered.age
is two times their dob.age
it possible?
EDIT:
As per advice in the comments I have tried it with map() and it sort of works
persons collection:
{ "_id" : 1, "test1" : 95, "test2" : 92, "test3" : 90, "modified" : ISODate("2020-01-04T18:30:00Z") }
{ "_id" : 2, "test1" : 98, "test2" : 100, "test3" : 102, "modified" : ISODate("2020-01-04T18:30:00Z") }
{ "_id" : 3, "test1" : 95, "test2" : 110, "modified" : ISODate("2020-01-03T18:30:00Z") }
Result:
[
undefined,
{
"_id" : 2,
"test1" : 98,
"test2" : 100,
"test3" : 102,
"modified" : ISODate("2020-01-04T18:30:00Z")
},
undefined
]
What I did not understand is why there are two undefined?
Also does this approach make use of indexing?
Yes. Short answer:
Array.forEach()
simply executes a function once for every element of the array. It doesn't return anything and, by itself, it doesn't do anything to modify or filter the array.Array.map()
also executes a function once for every element of the array, but each time it calls the function, it uses the function's return value to build a new array with the same number of elements as the input array.Array.filter()
is similar: it executes a function once for every element of the array, and it builds a new array, but it expects the function to return eithertrue
orfalse
. If the function returnstrue
, then it includes that element from the input array in the new array that it's building. If the function returnsfalse
, then it does NOT include that element from the input array in the new array that it's building.The reason you are getting
undefined
is you are usingArray.map()
, which is building a new array with the exact same number of elements as the input array. Your function is written so that it returnsdoc
if the condition is true, but if the condition is false, it returns nothing (undefined
).Array.filter()
is what you want. And you should make your function return eithertrue
orfalse
depending on whether you want that array element to be included in the output.Side note: My inclination would be to perform the comparison as a part of your database query, but to answer your question of whether or not you can do this locally in JavaScript, yes it can be done.