Dagrada
Dagrada

Reputation: 1155

Filter to match array exactly

My documents contain an array, for example;

{
    "a": [ 2, 3 ],
    "id":  ...
}

I want to return only the documents for which a contains only the elements 2 and 3.

This is the simplest I've found yet;

r.table("t").filter(r.row('a').difference([2,3]).eq([]))

Is there a better way?

Upvotes: 0

Views: 366

Answers (1)

Jorge Silva
Jorge Silva

Reputation: 4614

A nice way to write the same function would be to use .isEmpty instead of .eq([]).

r.table("t")
 .filter(r.row('a').difference([2,3]).isEmpty())

This query is equivalent to the function you wrote.

That being said, your current query returns document where a has only 2 and/or 3. So, for example, a document with with a: [2] would get matched.

Example result set:

{
  "a": [ 2 ] ,
  "id":  "f60f0e43-a542-499f-9481-11372cc386c8"
} {
  "a": [ 2, 3 ] ,
  "id":  "c6ed9b4e-1399-47dd-a692-3db80df4143c"
}

That might be what you want, but if you only want documents where the a property is [2, 3] or [3, 2] exactly and contains no other elements, you might want to just use .eq:

r.table("t")
 .filter(r.row('a').eq([2,3]).or( r.row('a').eq([3, 2]) ))

Example result:

{
  "a": [ 2, 3 ] ,
  "id":  "c6ed9b4e-1399-47dd-a692-3db80df4143c"
}, {
  "a": [ 3, 2 ] ,
  "id":  "cb2b5fb6-7601-43b4-a0fd-4b6b8eb83438"
}

Upvotes: 1

Related Questions