如果我有一個集合,如下所示:MongoDB的聚集投影
db.cafe.insert({name: "Cafe1", customers: [{name: "David", foods: [{name : "cheese"}, {name: "beef"}]}, {name: "Bill", foods: [{name: "fish"}]} ]})
db.cafe.find().pretty()
{
"_id" : ObjectId("54f5ae58baed23b7a34fccb6"),
"name" : "Cafe1",
"customers" : [
{
"name" : "David",
"foods" : [
{
"name" : "cheese"
},
{
"name" : "beef"
}
]
},
{
"name" : "Bill",
"foods" : [
{
"name" : "fish"
}
]
}
]
}
我如何可以提取只包含人稱爲「萬人迷」的食物對象的數組。 所需的輸出僅僅是食物的陣列,即:
[{name: "cheese"}, {name: "beef"}]
我試圖聚集流水線解開網吧客戶,然後在名稱匹配,那麼項目的食品,如:
db.cafe.aggregate([{$unwind : "$customers"}, {$match : {"customers.name": "David"}}, {$project : {"customers.foods": 1, _id : 0}
}]).pretty()
{
"customers" : {
"foods" : [
{
"name" : "cheese"
},
{
"name" : "beef"
}
]
}
}
這似乎接近理想的結果,但是,我留下的問題是,我想要的食物被稱爲屬性customers.foods下的數組。我想直接得到的結果是:
[
{
"name" : "cheese"
},
{
"name" : "beef"
}
]
有沒有一種方法可以實現所需的輸出?
我認爲你應該改變你的項目如下 '{「$ project」:{「_ id」:0,「food」:「$ customers.foods」}}' – Yogesh 2015-03-03 13:12:24