[英]MongoDB - Querying based on the value of a property of an array of objects
對MongoDB來說是全新的。 我很難通過嵌套在數組中的對象的屬性進行查詢。
我有以下數據結構:
{
"sales":[
{
"item":1234,
"seller":"SellerA",
"buyer":"BuyerA"
},
{
"item":5678,
"seller":"SellerB",
"buyer":"SellerB"
},
{
"item":1122,
"seller":"SellerA",
"buyer":"BuyerA"
},
{
"item":1199,
"seller":"SellerB",
"buyer":"SellerB"
}
]
}
我具有與“ sales”數組處於同一級別的其他屬性,但是對於該示例我進行了簡化。
我正在嘗試提取所有買方值為“ BuyerB”的銷售單據。
我嘗試了以下方法:
db.data.find({"sales": {$elemMatch: {buyer: "BuyerB"}}})
db.data.find({"sales.buyer": "BuyerB"}})
這些查詢會運行,但返回的是每一行數據,而不僅僅是返回買方值為“ BuyerB”的數據
我知道必須有一個簡單的答案,但是我搜索的結果就是我已經嘗試過但沒有成功的內容。
由於您可能從數組中返回多個元素,而.find()無法做到這一點,因此您可以嘗試進行聚合,例如:
db.c.aggregate({
$match : {
"sales.buyer" : "BuyerB"
}
}, {
$unwind : "$sales"
}, {
$match : {
"sales.buyer" : "BuyerB"
}
}, {
$group : {
_id : "$_id",
sales : {
$push : "$sales"
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.