2017-07-10 29 views
0

我正在使用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

+1

你不需要'這裏「單」 $ filter'比賽。如果你閱讀「全部」,給出的答案應該已經看到了'.find({「name」:「earth」,「cars.brand」:「tesla」},{「brand。$」:1})'返回相同的東西。至於它「不是你想要的」,那就習慣吧!您畢竟是決定將文檔嵌入到數組中的人。如果您希望僅檢索匹配的嵌入文檔,那麼「您」應該將它們放入單獨的集合中。你能做到嗎?是。你應該這樣做嗎?不需要。只需匹配數據並在代碼中提取項目 –

回答

1

您可以使用下面聚集管道:

db.users.aggregate([ 
{$match: {name:"earth"}}, 
{$unwind: "$cars"}, 
{$replaceRoot: {newRoot: "$cars"}}, 
{$match: {brand:"tesla"}} 
]); 
1

下面彙總查詢使用:

db.users.aggregate({$match:{name:'earth'}},{$unwind:"$cars"},{$match:{"cars.name":'tesla'}},{$project:{"cars":"$cars",_id: 0}}); 

結果會是這樣

{ "cars" : { "name" : "tesla", "color" : "red" } } 
1

我會說,而不是使用聚合,你可以達到規範盟友使用下面的查詢

db.users.find({ "name":"earth" }, { "cars" : { "$elemMatch" : { "name" : "tesla }}}) 

而你的輸出將是,

{ 
    "cars" : [ 
    { 
     brand : tesla 
     color : red 
     time : 123 
    }] 
} 

聚合始終是一個代價高昂的操作

相關問題