2017-07-04 97 views
0

所以我在我的人收藏了這些文件:如何在MongoDB查詢中過濾和映射文檔數組?

{ 
     "_id" : ObjectId("595c0630939a8ae59053a9c3"), 
     "name" : "John Smith", 
     "age" : 37, 
     "location" : "San Francisco, CA", 
     "hobbies" : [ 
       { 
         "name" : "Cooking", 
         "type" : "Indoor", 
         "regular" : true 
       }, 
       { 
         "name" : "Baseball", 
         "type" : "Outdoor", 
         "regular" : false 
       } 
     ] 
} 
{ 
     "_id" : ObjectId("595c06b7939a8ae59053a9c4"), 
     "name" : "Miranda Thompson", 
     "age" : 26, 
     "location" : "Modesto, CA", 
     "hobbies" : [ 
       { 
         "name" : "Lego building", 
         "type" : "Indoor", 
         "regular" : false 
       }, 
       { 
         "name" : "Yoga", 
         "type" : "Indoor", 
         "regular" : false 
       } 
     ] 
} 
{ 
     "_id" : ObjectId("595c078e939a8ae59053a9c5"), 
     "name" : "Shelly Simon", 
     "age" : 26, 
     "location" : "Salt Lake City, UT", 
     "hobbies" : [ 
       { 
         "name" : "Hunting", 
         "type" : "Outdoor", 
         "regular" : false 
       }, 
       { 
         "name" : "Soccer", 
         "type" : "Outdoor", 
         "regular" : true 
       } 
     ] 
} 

我想我的「愛好」濾鏡陣列只有到正規的愛好和項目領域_id,姓名,年齡和愛好的名稱和類型。

我希望我的輸出是這樣的:

{ 
     "_id" : ObjectId("595c0630939a8ae59053a9c3"), 
     "name" : "John Smith", 
     "age" : 37, 
     "hobbies" : [ 
       { 
         "name" : "Cooking", 
         "type" : "Indoor" 
       } 
     ] 
} 
{ 
     "_id" : ObjectId("595c06b7939a8ae59053a9c4"), 
     "name" : "Miranda Thompson", 
     "age" : 26, 
     "hobbies" : [] 
} 
{ 
     "_id" : ObjectId("595c078e939a8ae59053a9c5"), 
     "name" : "Shelly Simon", 
     "age" : 26, 
     "hobbies" : [ 
       { 
         "name" : "Soccer", 
         "type" : "Outdoor" 
       } 
     ] 
} 

嗯...我可以使用蒙戈外殼該命令實現這樣的輸出:

db.people.aggregate([ 
    { 
     $project: { 
      hobbies: { 
       $filter: { 
        input: "$hobbies", 
        as: "hobby", 
        cond: { $eq: ["$$hobby.regular", true] } 
       } 
      }, 
      name: 1, 
      age: 1 
     } 
    }, 
    { 
     $project: { 
      "hobbies.name": 1, 
      "hobbies.type": 1, 
      name: 1, 
      age: 1 
     } 
    } 
]) 

正如你所看到的,我不得不依次使用兩個$項目運營商,我認爲這味道不好。

是否有一種方法可以實現與另一個不使用相同運算符兩次並按順序的查詢相同的結果?

回答

2

您可以將$filter表達式包裝在$map內以映射輸出值。

db.people.aggregate([ 
    { 
    "$project": { 
     "name": 1, 
     "age": 1, 
     "hobbies": { 
     "$map": { 
      "input": { 
      "$filter": { 
       "input": "$hobbies", 
       "as": "hobbyf", 
       "cond": "$$hobbyf.regular" 
      } 
      }, 
      "as": "hobbym", 
      "in": { 
      "name": "$$hobbym.name", 
      "type": "$$hobbym.type" 
      } 
     } 
     } 
    } 
    } 
])