我正在使用mongo v3.4.4
如何獲取數組的對象。
採集樣品如何從Mongo中的數組中獲取對象
{
name: earth
age: 12
cars : [
{
brand : tesla
color : red
time : 123
},
{
brand : toyota
color : black
time : 124
},
]
},
{
name: mars
age: 15
cars : [
{
brand : volvo
color : green
time : 125
},
{
brand : honda
color : blue
time : 126
},
]
}
我只需要的是:
{
brand : tesla
color : red
time : 123
}
我曾嘗試:
db.users.aggregate([
{
$match:{"name":"earth"}
},
{
$project:
{"cars":
{"$filter":
{
input:"$cars",
as:"cars",
condition: "{$eq:[ $$cars.brand :"tesla"]}"
}
}
}
}
])
不過,我還沒有看到,我所期望的輸出。我不確定我是否沒有正確使用過濾器。如果cars數組中只有一個對象,那麼我只會返回一個對象。 我已經看過這個example
你不需要'這裏「單」 $ filter'比賽。如果你閱讀「全部」,給出的答案應該已經看到了'.find({「name」:「earth」,「cars.brand」:「tesla」},{「brand。$」:1})'返回相同的東西。至於它「不是你想要的」,那就習慣吧!您畢竟是決定將文檔嵌入到數組中的人。如果您希望僅檢索匹配的嵌入文檔,那麼「您」應該將它們放入單獨的集合中。你能做到嗎?是。你應該這樣做嗎?不需要。只需匹配數據並在代碼中提取項目 –