SORU
21 EKİM 2010, PERŞEMBE


MongoDB koleksiyon nesnesine bir dizi sadece sorgulanan öğeyi almak

Şu: varsayalım

// Document 1
{ "shapes": 
  [
    {"shape": "square", "color": "blue"},
    {"shape": "circle", "color": "red"}
  ] 
}


// Document 2
{ "shapes": 
  [
    {"shape": "square", "color": "black"},
    {"shape": "circle", "color": "green"}
  ] 
}

bunu sorgu:

db.test.find({"shapes.color": "red"}, {"shapes.color": 1})

ya

db.test.find({shapes: {"$elemMatch": {color: "red"}}}, {"shapes.color": 1})

döner şekiller eşleşen belge (Belge 1), ama her zaman TÜM dizi öğeleri:

{ "shapes": 
  [
    {"shape": "square", "color": "blue"},
    {"shape": "circle", "color": "red"}
  ] 
}

Ancak, belge 1) içeren bir dizi almak istiyorumcolor=kırmızı:

{ "shapes": 
  [
    {"shape": "circle", "color": "red"}
  ] 
}

Bunu nasıl yapabilirim?

CEVAP
3 EYLÜL 2012, PAZARTESİ


MongoDB 2.2 $elemMatch projeksiyon operatörler içeren iade belgeyi değiştirmek için başka bir yol sağlarilkshapes eleman eşleşti:

db.test.find(
    {"shapes.color": "red"}, 
    {_id: 0, shapes: {$elemMatch: {color: "red"}}});

Verir:

{"shapes" : [{"shape": "circle", "color": "red"}]}

2.2 de bu sorgudan $ projeksiyon nesne bir alan adını alan ilk eşleşen dizi öğenin dizinini gösterir $ projection operator kullanarak yapabilirsiniz. Aşağıdaki yukarıdaki gibi aynı sonuçları döndürür:

db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Jucyber Tutoriais

    Jucyber Tuto

    8 EYLÜL 2009
  • Julia Graf

    Julia Graf

    6 Mayıs 2006
  • theKGB65

    theKGB65

    24 Aralık 2007