I have a MongoDB document structured like this:
{
"user_id": 7387,
"first_name": "Daniel",
"roles": [
{
"role_id": "509c20144fd846549e8d42ef",
"role_name": "Writer",
"is_lead": 0
},
{
"role_id": "509c20344fd846549e8d42f0",
"role_name": "Editor",
"is_lead": 1
}
]
},
{
"user_id": 15735,
"first_name": "Tom",
"roles": [
{
"role_id": "509c203f4fd846549e8d42f1",
"role_name": "Admin",
"is_lead": 0
},
{
"role_id": "509c20144fd846549e8d42ef",
"role_name": "Writer",
"is_lead": 1
},
{
"role_id": "509c20344fd846549e8d42f0",
"role_name": "Editor",
"is_lead": 0
}
]
}
How do I find all users who have roles.role_name as Writer and roles.is_lead as 1 (all writers who are also a lead)?
I tried:
db.users.find({$and:[{"roles.role_name":"Writer","roles.is_lead":1}]});
In the above example, it should only return “Tom”. But this returns both “Tom” and “Daniel” (I guess it picks {roles.is_lead:1} for the Editor role of “Daniel”. How do I fix this query?
Thanks.
What you are looking for is
$elemMatchto make sure your search matches a specific element and not a mixture of any elements within the same document.Your original query was also the same as just doing a default basic search, since that will be an AND as well. The problem is that the AND was applying to any part of the document.