开发者

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

开发者 https://www.devze.com 2023-04-09 22:15 出处:网络
I have a collection in mongo where objects appear as follows: { name:\"Scott\", bio:\"Stumped\", roles:[\"USR\",\"ADM\"] }

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 que开发者_运维知识库ries w/ the application handling intersection. Ideas?


Found the answer:

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

Thanks Hohhi for leading me down the right path!


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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消