I have following documents in my collection:
/* 1 */
{
"_id" : ObjectId("5ea32d11f213c27c35395fd3"),
"name" : "Test",
"state" : "OH",
"code" : "CDM"
}
/* 2 */
{
"_id" : ObjectId("5ea32d29f213c27c35395fe0"),
"name" : "Test1",
"state" : "ALL",
"code" : "CDM"
}
/* 3 */
{
"_id" : ObjectId("5ea32d38f213c27c35395fe7"),
"name" : "Test2",
"state" : "OH",
"code" : "ALL"
}
/* 4 */
{
"_id" : ObjectId("5ea32d46f213c27c35395feb"),
"name" : "Test3",
"state" : "ALL",
"code" : "ALL"
}
Trying to filter documents based on state and code.
But there are few criteria if particular state or code is not found then search with value ALL
Example 1:
state = CA
code = CDM
then return only
{
"_id" : ObjectId("5ea32d29f213c27c35395fe0"),
"name" : "Test1",
"state" : "ALL",
"code" : "CDM"
}
Example 2:
state = CA
code = DCM
then return only
{
"_id" : ObjectId("5ea32d46f213c27c35395feb"),
"name" : "Test3",
"state" : "ALL",
"code" : "ALL"
}
etc..
The query that i tried was state = CA ,code = CDM:
db.getCollection('user_details').aggregate([
{'$match': { 'state': {'$in': ['CA','ALL']},
'code': {'$in': ['CDM','ALL']}}}
])
return was:
/* 1 */
{
"_id" : ObjectId("5ea32d29f213c27c35395fe0"),
"name" : "Test1",
"state" : "ALL",
"code" : "CDM"
}
/* 2 */
{
"_id" : ObjectId("5ea32d46f213c27c35395feb"),
"name" : "Test3",
"state" : "ALL",
"code" : "ALL"
}
Expected was :
{
"_id" : ObjectId("5ea32d29f213c27c35395fe0"),
"name" : "Test1",
"state" : "ALL",
"code" : "CDM"
}
Could you help to solve this issue.
{ "_id" : ObjectId("5ea32d46f213c27c35395feb"), "name" : "Test3", "state" : "ALL", "code" : "ALL" }if both are not found ?{ "_id" : ObjectId("5ea32d29f213c27c35395fe0"), "name" : "Test1", "state" : "ALL", "code" : "CDM" }&{ "_id" : ObjectId("5ea32d29f213c27c35395fe1"), "name" : "Test2", "state" : "CA", "code" : "CDM" }then what has to be returned - Only the 2nd Doc ?