0

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"}]}}} ]})
Beginner
  • 855
  • 9
  • 21
  • 37
  • I had already used $elemMatch but it is not giving me the desired results – Beginner Oct 23 '17 at 07:15
  • You have a mistake in your query. Just because you say you want to query on a field AND on another field doesn't mean you have to write it. Quote: $and performs a logical AND operation on an array of two or more expressions. Just remove the $and and add it in the $elemMatch condition. Example: "$elemMatch": {"attributeName": "Country", "attributeValue": "United States"} – Alex P. Oct 23 '17 at 08:09
  • Or you do it like this: "$elemMatch": { $and: [{ "attributeName": "Country", "attributeValue": "United States" }] } – Alex P. Oct 23 '17 at 08:14

0 Answers0