2017-01-29 21 views
0

Ich verwende mongodb 3.4.0 in MacOS Sierra 10.12.2mongodb Abfrage Subdokument in Array zurückgegeben all Dokument

meine Sammlung unten:

{ 
    "_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" 
       } 
      ] 
     } 
    ] 
} 

Ich habe die folgenden Abfragen verwenden

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" 
     } 
    } 
}) 

und immer wieder zurückkehrt alle Dokumente in box_location statt nur box_location in TW Ländercode.

Ich habe gesucht, hier Lösung und es erwähnen immer Punktnotation oder elemMatch aber keiner von ihnen arbeitet

Wenn ich Ländercode TW abfragen, sollte es nur

"box_location" : [ 
    { 
     "country" : "Taiwan", 
     "country_code" : "TW", 
     "location" : [ 
      { 
       "city" : "Taipei", 
       "name" : "Taipei 101" 
      } 
     ] 
    } 
] 

Antwort

0

ok Rück bekam es

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

Kasse doc hier https://docs.mongodb.com/v3.2/reference/operator/aggregation/unwind/

+0

verwenden können, während Sie das Ihr Problem gelöst haben, mit dem Code nur Antworten sind nicht sehr hilfreich für Benutzer, die in Zukunft auf diese Frage kommen. Bitte bearbeiten Sie Ihre Antwort, um zu erklären, warum Ihr Code das ursprüngliche Problem löst. –

+0

Sehen Sie sich bitte [Kann ich meine eigene Frage beantworten?] (Http://stackoverflow.com/help/self-answer) an und kommen Sie zwei Tage später zurück und überprüfen Sie, wie beantwortet. –

0

Sie $elemMatch im Projektionsparameter in find()

db.settings.find({ 
    "box_location.country_code":"TW" 
}, 
{ 
    _id : 0, 
    box_location : { 
    $elemMatch : { 
     country_code : "TW" 
    } 
    } 
}) 
Verwandte Themen