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ş:
nasıl mongodb birden fazla dizi öğeler...
Nasıl bir dizi alanı benzersiz bir değ...
Sadece statik alanları Java sınıfta bi...
Neden sadece C bir dizi içeren bir yap...
Dizi boş alan (Firavun faresi kullanar...