Scott
Scott

Reputation: 1010

How can I do $and queries against an array in Mongo?

I have a collection in mongo where objects appear as follows:

{ name:"Scott", bio:"Stumped", roles:["USR","ADM"] }

Many more roles are possible. I want to perform any combination of intersection queries, like so:

db.coll.find({$and:[{roles:"USR"},{roles:{$ne:"ADM"}}]})

Some queries may be all role =, some may be all roles !=, and some may be mixed as with the above example. I have had some measure of success with $or and $nor, but absolutely no query I can fathom works with $and. I have even tried leveraging $where and $elemMatch to emulate what I want. I am also really trying to avoid multiple queries w/ the application handling intersection. Ideas?

Upvotes: 1

Views: 448

Answers (2)

Scott
Scott

Reputation: 1010

Found the answer:

db.coll.find( {roles : { $all : ["USR"], $nin : ["ADM"]}} )

Thanks Hohhi for leading me down the right path!

Upvotes: 2

Yurii Hohan
Yurii Hohan

Reputation: 4171

db.coll.find("roles":{$all:["USR","ADM"]}})

I think this would help you, at least it returns the result you are looking for

Upvotes: 1

Related Questions