Find documents where array has only identical elements

42 views
Skip to first unread message

torn...@gmail.com

unread,
Jun 5, 2015, 2:40:13 PM6/5/15
to mongod...@googlegroups.com
Hello,
let's assume I have the following partial documents:

{StringArray: ["A","B","C"]}
{StringArray: ["A","A","A"]}
{StringArray: ["B","B","B"]}

Now i want to find all the documents where StringArray only contains "A" elements. Let's name this the ALL operation.

My current way is:
db.TestCollection.find({ StringArray: { $elemMatch: {$eq: "A"}, $not: {$elemMatch: {$ne: "A"}}}})

which makes sure that i only hit the documents where StringArray contains 'A'  AND does not contain anything which is not 'A'. (Without the first part it would also match empty arrays).

Now this works for the simple cases, for more complicated elemMatch expressions (regex, other logical operators) this is still possible, but gets complicated to build the appropriate negated expression.

It gets really complicated,  if I have multiple nested ALL operations (e.g. find all document where all the embedded documents all contain the string array above)

Has anyone a better idea on how to do this ALL operation without the need to manually build the negated expression?

Thanks,
Torni

Asya Kamsky

unread,
Jun 6, 2015, 1:14:26 AM6/6/15
to mongodb-user
How about using aggregation framework? Multiple possibilities exist...

db.collection.aggregate({$project:{numUniqueStringArray:{$size:
{$setDifference:["$StringArray", [] ]}}}}, {$match:{
numUniqueStringArray : 1 } } )

That works to find all documents where StringArray contains one or
more of any single letter. If you specifically want "A" you can use [
"A" ] as second argument to $setDifference and then match results that
are 0 only.

Asya
> --
> You received this message because you are subscribed to the Google Groups
> "mongodb-user"
> group.
>
> For other MongoDB technical support options, see:
> http://www.mongodb.org/about/support/.
> ---
> You received this message because you are subscribed to the Google Groups
> "mongodb-user" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to mongodb-user...@googlegroups.com.
> To post to this group, send email to mongod...@googlegroups.com.
> Visit this group at http://groups.google.com/group/mongodb-user.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/mongodb-user/9b031c26-8dcc-4813-bfdb-1791b29459a7%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

torn...@gmail.com

unread,
Jun 6, 2015, 4:05:29 AM6/6/15
to mongod...@googlegroups.com
Thanks for the example with the aggregation framework. I'll try that.
Reply all
Reply to author
Forward
0 new messages