Conditional query of complex array elements

35 views
Skip to first unread message

DaveC

unread,
Oct 6, 2012, 3:50:21 PM10/6/12
to mongod...@googlegroups.com
I've got a set of documents where I'm storing access control information in an array on each document. This access control information contains a "Group" and a "Right". I don't seem to be able to query based on both elements at once, as in, where a certain group has a certain right.  Here is example data:

{
  "Name": "Doc1",
  "Acl" : [ {"Group":"Users", "Right":"Read" } ]
},
{
  "Name": "Doc2",
  "Acl" : [ {"Group":"Users", "Right":"Read" }, { "Group" : "Admins", "Right": "Read" }, { "Group" : "Admins", "Right": "Delete" }]
},
{
  "Name": "Doc3",
  "Acl" : [ {"Group":"Admins", "Right":"Read" } ]
},
{
  "Name": "Doc4",
  "Acl" : [ {"Group":"Users", "Right":"Delete" } ]
}

I'd like to find the documents where members of the group "Users" have the right to "Delete". However, if I query like this:

db.docs.find({"Acl.Group":"Users", "Acl.Right":"Delete"})

then I get Doc2 and Doc4 because it matches on Acl.Group == "Users" OR Acl.Right == "Delete".  Is there some way to find docs with an Acl array element where Group = "Users" AND Right == "Delete"?  Is it possible without JavaScript?  I'm running 2.2, if that helps.

Thanks.

DaveC

unread,
Oct 6, 2012, 3:55:02 PM10/6/12
to mongod...@googlegroups.com
Answered my own question...$elemMatch seems to do the trick:

db.docs.find({"Acl":{$elemMatch:{"Group":"Users", "Right":"Delete"}}})
Reply all
Reply to author
Forward
0 new messages