MongoDB 选择可选字段或默认值(如果存在)

问题描述 投票:0回答:1

我尝试选择具有一些可选 i18n 属性的文档。
这意味着我喜欢接收文档的一些属性,如果存在“本地化”属性的所有“de”属性。
为了更好地理解,数据库中的文档如下所示。

{
  "_id" : ObjectId("643926af14c8821ad40f8b47"),
  "price" : 1.256,
  "vendor" : "Any Company",
  "blocked" : false
  "localized" : {
        "en" : {
          "name" : "water carafe",
          "description" : "Contents: 1x ... up closure."
        },
        "de" : {
          "name" : "Wasserkaraffe",
          "description" : "Inhalt: 1x ... up-Verschluss."
        },
        "nm" : {
          "name" : "Lorem ipsum dolor sit amet",
          "description" : "At vero eo ... o duo dolores."
        }
    },
  "PropertyB" : 124,
  "SomePropertyC" : "importen property"
}

但我只对这个感兴趣:

{
  "_id" : ObjectId("643926af14c8821ad40f8b47"),
  "price" : 1.256,
  "localized" : {
        "de" : {
          "name" : "Wasserkaraffe",
          "description" : "Inhalt: 1x ... up-Verschluss."
        }
    }
}

主要问题是我只想选择几个根字段和“de”字段。如果“de”不可用,则应选择并返回“en”。如果有可能,如果两种情况都不存在,返回第一个最好的,那将是令人难以置信的。最后我把文件变成了一个扁平的新文件

最后

{
  "_id" : ObjectId("643926af14c8821ad40f8b47"),
  "price" : 1.256,
  "localized" : {
        "de" : {
          "name" : "Wasserkaraffe",
          "description" : "Inhalt: 1x ... up-Verschluss."
        }
    }
}

最后,我将文件转换成一个平面的新文件。 $project(聚合)显然是为此提供的。到目前为止,这工作得很好。但是,文档的查询对我来说是不可能的。
有谁知道这是如何工作的?

mongodb mongodb-query aggregation-framework
1个回答
0
投票
db.collection.aggregate([
  {
    $project: {
      price: 1,
      localized: {
        $cond: {
          if: { $not: [ "$localized.de" ] },
          then: { en: "$localized.en" },
          else: { de: "$localized.de" }
        }
      }
    }
  }
])

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.