Filtering based on key/value in all objects in array in RethinkDB
-
21-12-2019 - |
Question
I have a RethinkDB table with records structured like this:
{
one: [
{
field: val,
foo: bar
},
{
field: val2
}
]
}
Now, if I do something like
reql = reql.filter(function(tb) {
return tb("one").contains(function(k) {
return k("field").eq(val);
});
});
I match all documents where one of the objects in the array on the key "one" has a key "field" with a value matching "val". However, what I want to do is to only match the documents where all of the objects in the array on the key "one" have keys "field" with values matching "val".
How can I do this?
Solution
You can map each element of the array to a boolean (whether the value for "field" is "val"), then reduce with a and
.
So something like this:
reql.filter(function(tb) {
return tb("one").map(function(element) {
return element("field").eq("val")
}).reduce(function(left, right) {
return left.and(right)
})
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow