是否有mongodb查询来合并特定mongodb文档中的字段

时间:2020-11-11 07:06:50

标签: java spring mongodb

因此,假设我有一个文档:

{
  "country": "USA",
  "capital": "Washington DC",
  "language": "English",
  "other": {
    "China": {
      "capital": "Shanghai",
      "language": "Chinese"
    },
    "Spain": {
      "capital": "Madrid",
      "language": "Spanish"
    }
  }
}

现在我要以以下方式返回我的文档:

{
  "country": "USA",
  "capital": "Washington DC",
  "language": "English",
}

当我选择国家作为“美国”但是当我将国家/地区设置为“西班牙”时,我希望mongodb查询将文档返回为:

{
  "country": "Spain",
  "capital": "Madrid",
  "language": "Spanish",
}

这些字段应根据“其他”字段中指定的国家/地区进行合并。 我该如何实现?

1 个答案:

答案 0 :(得分:0)

尝试这个:

country = "Spain"

db.collection.aggregate([
   // Make a uniform structure (why do you have 'USA' and 'other'?)
   { $replaceRoot: { newRoot: { $mergeObjects: ["$other", { USA: { capital: "$capital", language: "$language" } }] } } },
   { $project: { countries: { $objectToArray: "$$ROOT" } } },
   {
      $set: {
         countries: {
            $filter: {
               input: "$countries",
               cond: { $eq: ["$$this.k", country] }
            }
         }
      }
   },
   {
      $replaceRoot: {
         newRoot: {
            $mergeObjects: [
               { country: { $first: "$countries.k" } },
               { $first: "$countries.v" }]
         }
      }
   }
])