0

I am using mongodb 3.4.0 in MacOS Sierra 10.12.2

my collection is below:

{
    "_id" : ObjectId("58837a559caf2fc968adc64d"),
    "box_location" : [ 
        {
            "country" : "Taiwan",
            "country_code" : "TW",
            "location" : [ 
                {
                    "city" : "Taipei",
                    "name" : "Taipei 101"
                }
            ]
        }, 
        {
            "country" : "Hong Kong",
            "country_code" : "HK",
            "location" : [ 
                {
                    "city" : "Hong Kong",
                    "name" : "Hung Hom Station"
                }
            ]
        }
    ]
}

I have use the following queries

db.setting.findOne({"box_location.country_code":"TW"}, {box_location:1, _id:0})

db.setting.find({"box_location.country_code":"TW"}, {box_location:1, _id:0})

db.setting.find({
    "box_location": {
        $elemMatch :{
            "country_code":"TW"
        }
    }
})

and always return all document in box_location instead of just box_location in TW country code.

I have been searching solution here and it always mention dot notation or elemMatch but none of them works

When I query country code TW, it should return only

"box_location" : [ 
    {
        "country" : "Taiwan",
        "country_code" : "TW",
        "location" : [ 
            {
                "city" : "Taipei",
                "name" : "Taipei 101"
            }
        ]
    }
]
Mark Thien
  • 1,108
  • 2
  • 22
  • 35

2 Answers2

0

ok got it

db.setting.aggregate(
  {$unwind: "$box_location"},
  {$match: {"box_location.country_code": "TW"}}
)

Checkout doc here https://docs.mongodb.com/v3.2/reference/operator/aggregation/unwind/

Mark Thien
  • 1,108
  • 2
  • 22
  • 35
  • While you may have solved this your problem, code-only answers are not very helpful to users who come to this question in the future. Please edit your answer to explain why your code solves the original problem. – Joe C Jan 29 '17 at 08:17
  • Please have a look at [Can I answer my own question?](http://stackoverflow.com/help/self-answer) and come back two days later and check as answered. – help-info.de Jan 29 '17 at 09:30
0

You can use $elemMatch in the projection parameter in find()

db.settings.find({
  "box_location.country_code":"TW"
},
{
  _id : 0,
  box_location : {
    $elemMatch : {
      country_code : "TW"
    }  
  }
})
ares
  • 4,283
  • 6
  • 32
  • 63