2017-08-10 57 views
3

mongodb聚合查詢出現問題。映射數組中的可選字段

這是我使用

{ 
"_id":"" 
"authors" : [ 
     { 
      "name" : "aaa", 
      "city" : "xyz", 
      "book":{"name":"blah"} 
     }, 
     { 
      "name" : "bbb", 
      "city" : "abc", 
     }, 
     { 
      "name" : "ccc", 
      "city" : "xyz", 
      "book":{"name":"blah blah"} 
     }, ] 
} 

使用這種查詢 -

db.book.aggregate([ { $project: {"id":1, "authors.name":1, "authors.city":1, 
      "authors.books": 
     { 
      $let :{ 
       vars:{"book":{$ifNull:["$authors.book", "absent"]}}, 
       in: { 
        $cond: {if: {$eq:["$$book","absent"]}, 
          then:[], 
          else:["$author.book"]} 
        } 
       } 
     } 
     } 
     },{ $out :"book" }]) 

導致以下輸出 -

{ 
"_id":"" 
"authors" : [ 
     { 
      "name" : "aaa", 
      "city" : "xyz", 
      "books":[[{"name":"blah"}], 
        [{"name":"blah blah"}]] 
     }, 
     { 
      "name" : "bbb", 
      "city" : "abc", 
      "books":[[{"name":"blah"}], 
        [{"name":"blah blah"}]] 
     }, 
     { 
      "name" : "ccc", 
      "city" : "xyz", 
      "books":[[{"name":"blah"}], 
        [{"name":"blah blah"}]] 
     }, ] 
} 

這是非常接近的DB模式我需要/想要的 -

{ 
"_id":"", 
"authors" : [ 
     { 
      "name" : "aaa", 
      "city" : "xyz", 
      "books":[ 
        {"name":"blah"}, 
        {"genre":"blah1"}] 
     }, 
     { 
      "name" : "bbb", 
      "city" : "abc", 
      "books":[] 
     }, 
     { 
      "name" : "ccc", 
      "city" : "xyz", 
      "books":[ 
        {"name":"blah blah"}, 
      {"genre":"blah1"}] 
     } 
    ] 
} 

問題是,一個作者的書的價值被分配給所有的作者。如果只有一個作者,代碼可以正常工作,但在超過1個時會失敗。 尚未嘗試將值分配給流派, 使用MongoDB 3.2.16版,幫助我弄清楚我做錯了什麼以及如何糾正它。提前致謝。

回答

0

使用$map遍歷數組並將更改應用於book字段。

喜歡的東西

db.book.aggregate([ 
    { 
    "$project": { 
     "id": 1, 
     "authors": { 
     "$map": { 
      "input": "$authors", 
      "as": "mauthor", 
      "in": { 
      "name": "$$mauthor.name", 
      "city": "$$mauthor.city", 
      "book": { 
       "$let": { 
       "vars": { 
        "lbook": { 
        "$ifNull": [ 
         "$$mauthor.book", 
         "absent" 
        ] 
        } 
       }, 
       "in": { 
        "$cond": { 
        "if": { 
         "$eq": [ 
         "$$lbook", 
         "absent" 
         ] 
        }, 
        "then": [], 
        "else": [ 
         "$$mauthor.book" 
        ] 
        } 
       } 
       } 
      } 
      } 
     } 
     } 
    } 
    } 
]) 

或者更換$let + $eq$gt表達對各種類型BSON比較工作。

喜歡的東西

db.book.aggregate([ 
    { 
    "$project": { 
     "id": 1, 
     "authors": { 
     "$map": { 
      "input": "$authors", 
      "as": "mauthor", 
      "in": { 
      "name": "$$mauthor.name", 
      "city": "$$mauthor.city", 
      "book": { 
       "$cond": { 
       "if": { 
        "$gt": [ 
        "$$mauthor.book", 
        null 
        ] 
       }, 
       "then": [ 
        "$$mauthor.book" 
       ], 
       "else": [] 
       } 
      } 
      } 
     } 
     } 
    } 
    } 
])