I am looking for mongodb query to retrieve results from documents inside documents. I have collection like this :
{
"_id" : ObjectId("59e6ea30ef03f811538bagd4"),
"_class" : "xyz",
"name" : "Test1",
"attributes" : [
{
"attributeName" : "Country",
"includedAttributes" : [
{
"_id" : ObjectId("59ddffe7d1f2f34eb9d32dcf"),
"attributeValue" : "United States",
"attributeName" : "Country"
}
]
}
]
},
{
"_id" : ObjectId("59e6ea30ef03f811538bxed4"),
"_class" : "xyz",
"name" : "Test2",
"attributes" : [
{
"attributeName" : "Country",
"includedAttributes" : [
{
"_id" : ObjectId("59ddffe7d1f2g34eb9d32dcf"),
"attributeValue" : "Buffalo",
"attributeName" : "City"
}
]
}
]
},
{
"_id" : ObjectId("59e6ea30ef03f811538baef4"),
"_class" : "xyz",
"name" : "Test3",
"attributes" : [
{
"attributeName" : "City",
"includedAttributes" : [
{
"_id" : ObjectId("59ddffe7h1f2e34eb9d32dcf"),
"attributeValue" : "Chicago",
"attributeName" : "City"
}
]
}
]
}
And I want query for this condition inludedAttributes{attributeName : Country and attributeValue: United States} or inludedAttributes{attributeName : City and attributeValue: Buffalo}.
I tried below query, but it's giving me zero results :
db.getCollection('collection1').find({
"$or" : [ { "attributes" : { "$elemMatch" : { "includedAttributes" : { "$elemMatch" : { "attributeName" : "Country"}} , "$and" : [ { "attributeValue" : "United States"}]}}},
{ "attributes" : { "$elemMatch" : { "includedAttributes" : { "$elemMatch" : { "attributeName" : "City"}} , "$and" : [ { "attributeValue" : "Buffalo"}]}}} ]})