Is there a way using Mongoid (3.1.6) to filter out documents when a field of type Array contains a single, specific value?
For example, say I have the following 4 documents
{foo: ['a', 'b', 'c'], bar: 1}
{foo: ['b'], bar: 2}
{foo: ['a', 'c'], bar: 3}
{foo: [], bar: 4}
{bar: 5}
In this example I want to filter out all documents where field foo
contains only the value 'b'. If it contains 'b' and other values, or doesn't contain 'b' at all or even is empty then the document should be returned. So, when querying the above set of documents I should get back the documents where bar
is 1, 3, 4, and 5, but not the document with bar
= 2.
I finally found an answer to this one. Between finding some more up-to-date documentation than what I was originally using (see here) and some experimentation it turns out that you can do this:
FooBar.not.all_in(foo: ['b']).not.with_size(foo: 1)
This will select all documents except those with 'b' in the array and the array has a size of 1. Or in other words, documents where 'b' is the only element in the array will be filtered out.