Question

I am having a collection(say Employees), which is containing multiple documents. Each document has the following fields-

{
    "name":"John",
    "designation":"Product manager",
    "departmentID":['abpqr','def']
}
{
    "name":"David",
    "designation":"Senior s/w Engg",
    "departmentID":['abc','lmn']
}
{
    "name":"Mathew",
    "designation":"ODC head",
    "departmentID":['abpyz','xyz']
}

Now I want a mongo query to fetch the list of employees whose departmentID starts from 'abp'. It should be something like-
db.Employees.find({departmentID: {$in: {$regex:'^abp'}}})

Is it possible to fetch it by using a single query? If not then what is the alternate to get the result. I am using pymongo and the result I am expecting is-

{
    "name":"John",
    "designation":"Product manager",
    "departmentID":['abpqr','def']
},
{
    "name":"Mathew",
    "designation":"ODC head",
    "departmentID":['abpyz','xyz']
}
Was it helpful?

Solution

I think you don't need $in operator in order to perform a query with only one condition.

db.Employees.find({departmentID:{$regex:'^abp'}}) 

It should works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top