2017-10-20 51 views
0

我正在尋找解決方法,但找不到它。我感謝您的幫助。如何在使用可翻譯字段的MongoDB中更改響應

我有產品,如集合:

[ 
    { 
     "name": [ 
      { "es": "Producto 1" }, 
      { "en": "Product 1" } 
     ] 
     "reference": "PR1", 
     "price": "20", 
     "description": [ 
      { "es": "Descripción 1" }, 
      { "en": "Description 1" } 
     ] 
    } 
] 

而且我想這樣做:

db.products.aggregate(); //通過語言ES例如查找:

並獲得:

[ 
    { 
     "name": "Producto 1", 
     "reference": "PR1", 
     "price": "20", 
     "description": "Descripción 1" 
    } 
] 

非常感謝。

+0

這是不可能與find。你必須使用聚合或替代。你的完整json是怎樣的? –

+0

嗨,亞歷克斯,感謝您的快速回答。你能否提供一個使用聚合的例子來得到這個迴應?謝了哥們。 – Jorge

回答

0

我建議架構更改,雖然這樣:

[ 
     { 
      "name" : [ 
       { 
        "language" : "es", 
        "description" : "Producto 1" 
       }, 
       { 
        "language" : "en", 
        "description" : "Product 1" 
       } 
      ], 
      "reference" : "PR1", 
      "price" : "20", 
      "description" : [ 
       { 
        "language" : "es", 
        "description" : "Descripción 1" 
       }, 
       { 
        "language" : "en", 
        "description" : "Description 1" 
       } 
      ] 
     } 
] 

原因,那麼你可以實際上你的情況語言組。 如果這是可能的,那麼你可以做到以下幾點:因爲你沒有提供完整的JSON

db.products.aggregate([ 
{$unwind: "$someName"}, 
{$unwind: "$someName.name"}, 
{$unwind: "$someName.description"}, 
{ 
    $group: { 
     _id: {namelang: "$someName.name.language", namedesc: "$someName.description.language"}, 
     name: {$first: "$someName.name.description"}, 
     reference: {$first: "$someName.reference"}, 
     price: {$first: "$someName.price"}, 
     description: {$first: "$someName.description.description"} 
    } 
}, 
{ 
    $match: { 
     "_id.namelang": "en", 
     "_id.namedesc": "en" 
    } 
} 
]) 

FYI我創建一個隨機的。這裏是完整的模式:

{ 
    "_id" : ObjectId("59ea07a600f5db2660dbf162"), 
    "someName" : [ 
     { 
      "name" : [ 
       { 
        "language" : "es", 
        "description" : "Producto 1" 
       }, 
       { 
        "language" : "en", 
        "description" : "Product 1" 
       } 
      ], 
      "reference" : "PR1", 
      "price" : "20", 
      "description" : [ 
       { 
        "language" : "es", 
        "description" : "Descripción 1" 
       }, 
       { 
        "language" : "en", 
        "description" : "Description 1" 
       } 
      ] 
     } 
    ] 
} 
相關問題