簡體   English   中英

如何將數據從一種結構遷移到另一種結構?

[英]How do I migrate my data from one structure to another?

我有一個 MongoDB 和 3 個 collections。這是 3 個 collections,每個都有一個它包含的文檔示例:

tag

_id: ObjectId('61b873ec6d075801f7a97e18')
name: 'TestTag'
category: 'A'

computer

_id: ObjectId('6098c5ab615d9e23543d0f6f')
name: 'TestComputer'
category: 'A',
tags: [
    ObjectId('61b873ec6d075801f7a97e18')
]

setting

_id: ObjectId('61e56339b528bf009feca149')
name: 'TestSetting'
category: 'A',
tags: [
    ObjectId('61b873ec6d075801f7a97e18')
]

如您所見,所有 3 個文檔都有一個category屬性,最后兩個文檔有一個tags屬性。 這個想法是您可以創建一個標簽並使用該標簽標記您的計算機和設置,但只能在同一類別中。

現在我正在嘗試 go 從tagsgroups ,所以我沒有標記計算機和設置,而是創建了一個新的組集合,如下所示:

groups

_id: ObjectId('63d2929c2c71e51f8ffcc921')
name: 'TestGroup'
category: 'A'
computers: []
settings: []

我想從標簽“遷移”到 因此,對於我的標簽集合中的每個標簽,我想創建一個具有相同名稱和相同類別的組。 對於標有該標簽的每台計算機和設置,我想將它們的 _id 添加到組中的計算機和設置 arrays。

因此,如果我們采用我展示的文檔,它將創建以下組:

_id: ObjectId('63d26d582c71e51f8ffcc8aa')
name: 'TestTag'
category: 'A'
computers: [
    ObjectId('6098c5ab615d9e23543d0f6f')
]
settings: [
    ObjectId('61e56339b528bf009feca149')
]

我如何進行這樣的查詢?

首先執行$group按類別和名稱對所有tags進行分組。 然后, $lookupcomputersetting以查找匹配的記錄。 最后,稍微整理一下$lookup結果並將$merge / $out groups到集合中。

db.tag.aggregate([
  {
    $group: {
      _id: {
        name: "$name",
        category: "$category"
      },
      tags: {
        "$addToSet": "$_id"
      }
    }
  },
  {
    "$lookup": {
      "from": "computer",
      "localField": "tags",
      "foreignField": "tags",
      "let": {
        c: "$_id.category"
      },
      "pipeline": [
        {
          $match: {
            $expr: {
              $eq: [
                "$$c",
                "$category"
              ]
            }
          }
        },
        {
          $project: {
            "_id": 1
          }
        }
      ],
      "as": "computers"
    }
  },
  {
    "$lookup": {
      "from": "setting",
      "localField": "tags",
      "foreignField": "tags",
      "let": {
        c: "$_id.category"
      },
      "pipeline": [
        {
          $match: {
            $expr: {
              $eq: [
                "$$c",
                "$category"
              ]
            }
          }
        },
        {
          $project: {
            "_id": 1
          }
        }
      ],
      "as": "settings"
    }
  },
  {
    $project: {
      _id: 0,
      name: "$_id.name",
      category: "$_id.category",
      computers: {
        "$map": {
          "input": "$computers",
          "as": "c",
          "in": "$$c._id"
        }
      },
      settings: {
        "$map": {
          "input": "$settings",
          "as": "s",
          "in": "$$s._id"
        }
      }
    }
  },
  {
    "$merge": {
      "into": "groups",
      "on": "_id",
      "whenMatched": "merge"
    }
  }
])

蒙戈游樂場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM